简体   繁体   中英

Why does a memory leak occur in this code when a bad_alloc exception is thrown for T2

If T2 were to throw, why would this cause T1 to have a memory leak?

// In some header file: void f( T1*, T2* );

// At some call site: f( new T1, new T2 );

If the second object's constructor throws an exception, then f() won't get called, so the code inside f() won't have any chance to either delete the first object that was created, or to store a pointer to that object for later deletion.

Similarly, the code that might execute after the exception is raised (eg in any catch handler-block that you might have set up to handle the exception) will not have access to a pointer to either object, so it won't be able to delete the created object either.

Therefore, it's more-or-less(*) inevitable that the object will leak in that scenario.

(Note that it is unspecified which function-argument will get evaluated first, so it could just as easily be T1() that throws after a T2 is created, causing a T2 object to get leaked instead)

(*) I suppose you could do something crazy like having the final line in your T1() and T2() constructors store their this -pointers into a static data-structure somewhere, but that would be really ugly and introduce a number of other problems; the proper solution to this problem would be to use std::unique_ptr or similar to "capture" the objects so that an explicit delete call is never necessary, and therefore no memory leak is possible regardless of when an exception gets thrown.

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