Is it safe to use
vector.emplace_back( new MyPointer() );
Or could an exception thrown or some failure inside vector cause memory leak?
Would it be better to do some form of the following, where you put the pointer in a temporary unique_ptr first.
vector.emplace_back( std::unique_ptr<MyPointer>( new MyPointer() ) );
So if a vector failure occurs the temporary unique_ptr will still clean up the memory?
It is not safe and would create a memory leak if you use the first version. The documentation says that if an exception is thrown, the call to
emplace
has no effect - which means the plain pointer you passed in is never deleted.You can use
or with C++14 you can use
or, if C++14 is not yet available, just roll your own version of
make_unique
. You can find it here.No, the first scenario is not safe and will leak memory if the
vector
throws an exception.The second scenario will not compile, as a
std::unique_ptr<T>
cannot be implicitly converted toT*
. Even if it could, this scenario is arguably worse than the first, because it will add the pointer to your vector, then immediately delete the object being pointed to. You will be left with a vector containing a dangling pointer.Without changing the type of your
std::vector
(which I assume isstd::vector<MyPointer*>
) there are two ways to make this code exception safe.Using C++11:
Or the more verbose C++03 way:
If you are able to change the type of your
std::vector<MyPointer*>
then the easiest method are those suggested by Daniel Frey above:Or with C++14: