zoukankan      html  css  js  c++  java
  • [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()
    ";
    32     World oneMoreWorld(3);
    33 
    34     return 0;
    35 }

    输出结果

    Matter from 1 
    Hello from 1
    Matter from 2 
    Hello from 2 
    Hello from main()
    Matter from 3 
    Hello from 3
    Bye from 3
    Matter Bye from 3
    Bye from 2
    Matter Bye from 2
    Bye from 1
    Matter Bye from 1
  • 相关阅读:
    [设计模式]门面模式
    [设计模式]装饰者模式
    IE8半透明不显示出文字
    解决IE6,IE7不能隐藏绝对定位溢出的内容
    [设计模式]适配器模式
    linux学习网站
    PPP协议解析
    c语言面试题__指针篇
    单链表反转
    16道C语言面试题
  • 原文地址:https://www.cnblogs.com/hustcser/p/3894953.html
Copyright © 2011-2022 走看看