在main()的末尾调用析构函数;奇怪的行为 [英] Is destructor called at the end of main(); strange behavior

查看:202
本文介绍了在main()的末尾调用析构函数;奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

那么为什么要同时执行语句A和B?

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

我见过以下变体,其中 void exec(); int exec(); main 函数以

结尾return foo.exec(); 这会调用析构函数吗?

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.

推荐答案

一旦主调用析构函数函数返回,即在 return 语句之后,就像其他任何函数中的本地对象一样。

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

至于 return someObject.someFunction(); ,在 return 语句中的表达式必须在<$之前被完全求值。 c $ c> return 语句实际上可以返回任何内容,因为它需要该表达式的结果。因此,如果该函数包含一个长时间运行的循环(如GUI事件循环),则 return 语句实际返回之前可能要花费一些时间。

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.

这篇关于在main()的末尾调用析构函数;奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆