首页 > 代码库 > [C++]对象的销毁机制

[C++]对象的销毁机制

销毁时会按照从后向前的顺序销毁,也就是说,越在后面定义的对象会越早销毁。其中的原因就是函数是在栈中保存的,因此,先定义的对象先压栈,所以在退栈时就会后销毁。而如果参数有多个的话,大多数编译器是从右开始压栈的,也就是参数列表最右边的变量最先压栈,所以参数列表最右边的变量会在最后销毁。

代码如下:

 1 #include<iostream> 2  3 using namespace std; 4  5 class Matter { 6 public: 7     Matter(int id) : _identifier(id)  8         {cout << "Matter from " << _identifier << endl; } 9     ~Matter()10         { cout << "Matter Bye from " << _identifier << endl; }11 12 private:13     const int _identifier;14 };15 16 class World {17 public:18     World(int id) : _identifier(id),_matter(id)19         {cout << "Hello from " << _identifier << endl; }20     ~World() { cout << "Bye from " << _identifier << endl; }21 22 private:23     const int _identifier;24     Matter _matter;25 };26 27 World TheWorld(1);28 29 int main() {30     World smallWorld(2);31     cout << "hello from main()\n";32     World oneMoreWorld(3);33 34     return 0;35 }

输出结果

Matter from 1 Hello from 1Matter from 2 Hello from 2 Hello from main()Matter from 3 Hello from 3Bye from 3Matter Bye from 3Bye from 2Matter Bye from 2Bye from 1Matter Bye from 1