c++ - C++中构造函数和析构函数的执行顺序

标签 c++ constructor destructor

我有一些 C++ 代码,带有构造函数和析构函数。

#include <iostream> 
using namespace std; 
class K { 
public: 
    K(){cout<< "3 ";} 
    ~K(){cout<< "1 ";} 
}; 
int main() 
{ 
    { 
        K a; 
        { 
            K b; 
        } 
        { 
            K c; 
        } 
    } 
    system("pause"); 
    return 0; 
}

问题: 我不明白为什么答案是:331311

而不是:333111

我知道第一个运行的构造函数和最后一个析构函数但是倒置了。

最佳答案

如果正确对齐,您的代码将更容易理解:

int main() 
{ 
    { 
        K a;  // a is being constructed
        { 
            K b; // b is being constructed
        } // b is being destructed
        { 
            K c; // c is being constructed
        } // c is being destructed
    } // a is being destructed

    system("pause");
    return 0; 
}

一般规则是,本地(自动)分配的变量仅存在于其范围内。

{
    SomeType a; // Creation
} // all local variables from matching { are destroyed

关于c++ - C++中构造函数和析构函数的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17211600/

相关文章:

C# - "destructors are not inherited"实际上是什么意思?

c++ - 析构函数中的 GMock 总线错误

java - 使用 self(this) 参数在构造函数中调用构造函数

c++ - 为什么C++在创建数组时不允许 `new`调用构造函数

c++ - 有问题的代码???我的析构函数有问题吗?

c++ - 为什么不为动态加载的 Qt 插件类调用析构函数?

c++ - Qt 渲染图像并显示它

C++如何使用CWnd *对象加载图片?

c++ - 在 C++ 中链接可调用对象

c# - 委托(delegate)给实例方法不能有 null 'this'