gpt4 book ai didi

c++ - RAII 失败 - 为什么此 C++ 代码会泄漏? - 在 try block 中放入 ctor 可防止 dtor

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:21 24 4
gpt4 key购买 nike

下面程序的输出是:

begin try
Object() ctor
begin catch

为什么不调用 Holder 类的析构函数?这是内存泄漏吗?是否可以在不重新抛出的情况下调用 Holder 类的析构函数?

#include <iostream>
#include <exception>


class Object
{
public:
Object() { std::cout << "Object() ctor" << std::endl; }
~Object() { std::cout << "~Object() dtor" << std::endl; }
};

class Holder
{

public:
Holder() :myObjectP( new Object() )
{
throw std::exception();
}
~Holder()
{
std::cout << "~Holder()" << std::endl;
delete myObjectP;
}
private:
Object* myObjectP;

};

int main(int argc, char* argv[])
{
try
{
std::cout << "begin try" << std::endl;
Holder h;
}
catch ( ... )
{
std::cout << "begin catch" << std::endl;
}
return 0;
}

最佳答案

在这种情况下,您的Holder 对象h 没有完全构建,也就是说h 的构造函数之前没有完成构建堆栈展开过程已经开始。

C++11 15.2 Constructors and destructors(2)

An object of any storage duration whose initialization or destructionis terminated by an exception will have destructors executed for allof its fully constructed subobjects (excluding the variant members ofa union-like class), that is, for subobjects for which the principalconstructor (12.6.2) has completed execution and the destructor hasnot yet begun execution.

关于c++ - RAII 失败 - 为什么此 C++ 代码会泄漏? - 在 try block 中放入 ctor 可防止 dtor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com