Is destructor called at the end of main(); strange behavior

南楼画角 提交于 2019-12-11 16:46:19

问题


// Foo.h

class Foo
{

public:
    Foo();
    ~Foo();
    void exec();
};


// Foo.cpp

Foo::~Foo()
{
    // Statements A
    exit(0);
}

//main.cpp

int main()
{
    Foo foo;
    foo.exec();

    // Statements B
    return 0;
}

So why both Statements A and B get executed? And is the destructor called when we reach return 0?

I have seen variants where void exec(); is int exec(); and the main function ends with
return foo.exec(); does this calls the destructor?

Because I want to have an object that takes control of the code flow from the main function and end the program later.


回答1:


The destructor, and hence statement A, is executed as part of the processing of the return 0 statement B. This is a simple guarantee in C++, that the destructor of a local object with automatic storage, is executed automatically when the execution leaves the object's scope.




回答2:


The destructor is called once the main function returns, i.e. after the return statement, just like local objects in any other function.

As for return someObject.someFunction();, the expression in the return statement must be fully evaluated before the return statement can actually return anything, because it needs the result of that expression. So if the function contains a long-running loop (like a GUI event loop) then it might take quite some time before the return statement actually returns.



来源:https://stackoverflow.com/questions/27387000/is-destructor-called-at-the-end-of-main-strange-behavior

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