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

I read the instruction that says ( http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared ):

In addition, f(shared_ptr<int>(new int(42)), g()) can lead to a memory leak if g throws an exception. This problem does not exist if make_shared b.

Why would this lead to a memory leak?

+6
source share
1 answer

The compiler is allowed to evaluate this 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 selected object is never deleted.

Using make_shared , nothing can happen between the distribution of an object and the initialization of a smart pointer to manage it.

+18
source

Source: https://habr.com/ru/post/954703/


All Articles