injoy
injoy

Reputation: 4383

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?

Upvotes: 7

Views: 1328

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254751

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.

Upvotes: 19

Related Questions