繁体   English   中英

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

[英]Order of execution of constructors and destructors in c++

我有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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM