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
  • 相关阅读:
    JavaScript OOP 思想
    单页界面和 AJAX 模式
    jQuery 的 ready 函数是如何工作的?
    Dojo系列教程
    谈谈javascript语法里一些难点问题(一)
    2014年总结、2015年的小计划--女生程序员小感想
    Android名词解释
    【JS】defer / async
    关于对defer的理解.
    defer和async的区别
  • 原文地址:https://www.cnblogs.com/hustcser/p/3894953.html
Copyright © 2011-2022 走看看