简体   繁体   中英

How memory leak can happen in this code

Here I read an example which can leak memory

void foo(std::shared_ptr<int> p, int init)
{
  *p = init;
}
foo(std::shared_ptr<int>(new int(42)), seed()); // assume seed() returns an int

The article says if seed() throws, then there will be a memory leak. I am not understanding how?

If the shared_ptr is created first, and then seed() throws an exception, during stack unwinding, the temporary shared-ptr will be destroyed, deallocating the memory. If seed() throws error beforehand, then there will be no allocation at the first place.

What I am missing?

the order of execution can be

auto temp = new int(42);
auto temp2 = seed(); // if throw exception, temp is leaked
auto temp3 = std::shared_ptr<int>(temp);
foo(temp3, temp2);

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