简体   繁体   English

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

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

i have c++ little code, with constructors and destructors. 我有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; 
}

problem: i don't understand why answer is: 331311 问题:我不明白为什么答案是: 331311

and not: 333111 . 而不是333111

i know that first running constructors and last destructors but inverted. 我知道第一个运行的构造函数和最后一个析构函数但倒置了。

Your code will be a lot easier to understand if it is aligned properly: 如果正确对齐,您的代码将更容易理解:

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

The general rule is, that a locally (automatically) allocated variable lives only inside its scope. 一般规则是,局部(自动)分配的变量仅存在于其范围内。

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

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

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