Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there memory leak while using shared_ptr as a function parameter?

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?

like image 227
injoy Avatar asked Sep 26 '13 17:09

injoy


People also ask

Does function create memory leak?

No it does not cause memory leaks.

Why would you choose shared_ptr instead of Unique_ptr?

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.

What happens when you move a shared_ptr?

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).

What happens when shared_ptr goes out of scope?

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.


1 Answers

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.

like image 128
Mike Seymour Avatar answered Sep 20 '22 23:09

Mike Seymour