RAII Failure - Why Does this C++ Code Leak? - throw in ctor in try block prevents dtor

不想你离开。 提交于 2021-02-10 13:10:37

问题


The output of the program below is:

begin try
Object() ctor
begin catch

Why is the Holder class's destructor not called? Is this a memory leak? Is it possible to call the Holder class's destructor without rethrowing?

#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;
}

回答1:


In this case, your Holder object h is not fully constructued, that is that h's constructor had not finished its construction before the stack unwinding process had begun.

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.



来源:https://stackoverflow.com/questions/35858184/raii-failure-why-does-this-c-code-leak-throw-in-ctor-in-try-block-prevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!