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

标签 c++ memory-leaks error-handling exception

下面程序的输出是:

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 destruction is terminated by an exception will have destructors executed for all of its fully constructed subobjects (excluding the variant members of a union-like class), that is, for subobjects for which the principal constructor (12.6.2) has completed execution and the destructor has not yet begun execution.

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

相关文章:

android - 我该怎么做才能避免我的 Android 应用程序发生内存泄漏?

scala - 避免 Scala 内存泄漏 - Scala 构造函数

ios - 更改图像色调颜色内存泄漏

c++ - 提供纯虚函数的定义

c++ - 语法问题

c++ - map 的 Lambda 键比较器

perl - 如何正确处理Perl中的错误

vbscript - 如何忽略VBScript中的Internet错误?

debugging - 最佳错误修复/错误发现策略-所有语言

C++ For 循环遍历结构 vector (包含更多结构 vector )