Constructor finishes by throwing an exception ? Is there a memory leak?(构造函数以抛出异常结束?是否存在内存泄漏?)
问题描述
我正在阅读这篇它指出
注意:如果构造函数以抛出异常结束,内存与对象本身相关联的被清理——没有内存泄漏.例如:
Note: if a constructor finishes by throwing an exception, the memory associated with the object itself is cleaned up — there is no memory leak. For example:
void f()
{
X x; // If X::X() throws, the memory for x itself will not leak
Y* p = new Y(); // If Y::Y() throws, the memory for *p itself will not leak
}
我很难理解这一点,如果有人能澄清这一点,我将不胜感激.我尝试了以下示例,该示例表明构造函数中发生异常时不会调用析构函数.
I am having difficulty understanding this and would appreciate it if someone could clarify this. I tried the following example which shows that incase of an exception inside a constructor the destructor would not be called.
struct someObject
{
someObject()
{
f = new foo();
throw 12;
}
~someObject()
{
std::cout << "Destructor of someobject called";
}
foo* f;
};
class foo
{
public:
foo()
{
g = new glue();
someObject a;
}
~foo()
{
std::cout << "Destructor of foo";
}
private:
glue* g;
};
int main()
{
try
{
foo a;
}
catch(int a)
{
//Exception caught. foo destructor not called and someobject destrucotr not called.
//Memory leak of glue and foo objects
}
}
我该如何解决这个问题?
How would I fix this issue ?
对于更新可能给您带来的不便,我们深表歉意.
Sorry for the inconvenience the update might have caused.
推荐答案
...不会调用析构函数."
由于对象还没有被认为是已构造的,所以在构造函数因异常而失败后,不会调用析构函数.
Since the object isn't considered as constructed yet, after the constructor failed with an exception, the destructor won't be called.
对象分配和构造(只是销毁)是不同的东西.
Object allocation, and construction (merely destruction) are different things.
在抛出异常之前使用 new()
分配的任何对象都会泄漏.
Any objects allocated using new()
before the exception is thrown will leak.
您不应该自己管理这些资源,除非您真的、真的、真的需要它,并且大约 100% 确定自己在做什么.
You shouldn't manage these resources yourself, unless you're really, really, really need it, and are about 100% sure about what you're doing.
而是为来自标准动态内存管理库的类成员使用合适的智能指针.
Rather use suitable smart pointers for class members from the standard dynamic memory management library.
这篇关于构造函数以抛出异常结束?是否存在内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:构造函数以抛出异常结束?是否存在内存泄漏?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01