简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM