0

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

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

4

1 回答 1

8

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

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
于 2013-06-20T10:47:05.557 回答