No, the first scenario is unsafe and there will be a memory leak if vector throws an exception.
The second script will not compile, since std::unique_ptr<T> cannot be implicitly converted to T* . Even if itβs possible, this scenario is probably worse than the first because it will add a pointer to your vector and then immediately delete the object that it points to. You will be left with a vector containing a dangling pointer.
Without changing the type of your std::vector (which I assume std::vector<MyPointer*> ) there are two ways to make this code safe.
Using C ++ 11:
auto ptr = std::unique_ptr<MyPointer>(new MyPointer()); vector.emplace_back(ptr.get()); ptr.release();
Or a more detailed C ++ 03 way:
MyPointer* ptr = new MyPointer(); try { vector.push_back(ptr); } catch (...) { delete ptr; throw; }
If you can change the type of your std::vector<MyPointer*> , then the easiest way are the methods suggested by Daniel Frey above:
std::vector<std::unique_ptr<MyPointer>> vector; vector.emplace_back(std::unique_ptr<MyPointer>(new MyPointer()));
Or with C ++ 14:
std::vector<std::unique_ptr<MyPointer>> vector; vector.emplace_back(std::make_unique<MyPointer>());
marack
source share