简体   繁体   English

为什么当 T2 抛出 bad_alloc 异常时,此代码中会出现 memory 泄漏

[英]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?如果 T2 要抛出,为什么这会导致 T1 出现 memory 泄漏?

// In some header file: void f( T1*, T2* ); // 在一些 header 文件中: void f( T1*, T2* );

// At some call site: f( new T1, new T2 ); // 在某个调用点: 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.如果第二个对象的构造函数抛出异常,则f()不会被调用,因此f()中的代码将没有机会删除创建的第一个 object,或存储指向该 object 的指针供以后删除。

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.同样,在引发异常后可能执行的代码(例如,在您可能设置为处理异常的任何catch处理程序块中)将无法访问指向 object 的指针,因此它将无法删除创建的 object 或者。

Therefore, it's more-or-less(*) inevitable that the object will leak in that scenario.因此,在这种情况下,object 或多或少(*)不可避免地会泄漏。

(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) (请注意,未指定首先评估哪个函数参数,因此它很容易在创建T2后引发T1() ,从而导致T2 object 被泄露)

(*) 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; (*) 我想你可以做一些疯狂的事情,比如让T1()T2()构造函数中的最后一行将它们的this指针存储到 static 数据结构的某个地方,但这真的很难看,并引入了许多其他的问题; 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.解决此问题的正确方法是使用std::unique_ptr或类似的“捕获”对象,以便永远不需要显式delete调用,因此无论何时抛出异常都不会发生 memory 泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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