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++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01