简体   繁体   中英

temporarily cast a unique_ptr to a raw pointer

I have a question regarding smart pointers. Is it possible to temporarily cast a smart pointer to a raw pointer? For example:

std::vector<std::unique_ptr<monster>> all_monsters to std::vector <monster*> all_monsters ;? I have been looking everywhere on the internet but can't find a method

I have a std::vector <monster*> all_monsters and I have another vector called std::vector <monster*> monsters which has objects that should be deep copied into all_monsters. So I use this for loop to do so

  for (unsigned i=0; i < monsters.size(); i++) 
{            all_monsters.push_back(new monster(monsters[i]->getMonster(),monsters[i]->getCost(),monsters[i]->getType()));
     }

However I don't want to be manually deleting the objects so I want to use a unique pointer. That's why I changed my vector to std::vector<std::unique_ptr<monster>> all_monsters; and my for loop to

for(unsigned i = 0; i < monsters.size(); i++)
{

       all_monsters.push_back(std::make_unique<monster>(all_monsters[i]->getName(),all_monsters[i]->getManaCost(),all_monsters[i]->getType()));

}

but I have a function that only takes std::vector <monster*> as input (which can not be changed) that's why I want to temporarily cast the shared pointer to a raw pointer. Am I thinking too complicated?

You can certainly get a single raw pointer from a single std::unique_ptr , using the get() member function.

But you cannot safely cast a std::vector of one type to a std::vector of a different type.

So if the other function's interface can't be changed, you'll unfortunately need an extra step to build its vector argument:

std::vector<monster*> tmp_monsters;
std::transform(all_monsters.begin(), all_monsters.end(),
               back_inserter(tmp_monsters),
               [](const std::unique_ptr<monster>& mon_in) { return mon_in.get(); });
other_function(tmp_monsters);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM