I read a manual saying that (see http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared):
Moreover,
f(shared_ptr<int>(new int(42)), g())
can lead to memory leak if g throws an exception. This problem doesn't exist if make_shared is used.
Why would that lead to memory leak?
No it does not cause memory leaks.
Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.
By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).
All the instances point to the same object, and share access to one "control block" that increments and decrements the reference count whenever a new shared_ptr is added, goes out of scope, or is reset. When the reference count reaches zero, the control block deletes the memory resource and itself.
The compiler is allowed to evaluate that expression in the following order:
auto __temp1 = new int(42);
auto __temp2 = g();
auto __temp3 = shared_ptr<int>(__temp1);
f(__temp3, __temp2);
You can see that if g()
throws, then the allocated object is never deleted.
Using make_shared
, nothing can come between allocating the object and initialising the smart pointer to manage it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With