I just stumbled upon a code like this:
std::vector<std::unique_ptr<Fruit>> fruits;
fruits.emplace_back(new Fruit);
So in the code we have a raw pointer (new
produces a raw pointer, right?) pushed into a vector of unique pointers. And the code works! But why?
Because this does not compile:
std::unique_ptr<Fruit> f = new Fruit();
Is it a bit of under-the-hood magic, for convenience?
Also, what are the possible pitfalls of this approach instead of explicit fruits.emplace_back(std::make_unique<Fruit>())
? I've read that make_unique
is the preferred method of creating unique pointers.