zoukankan      html  css  js  c++  java
  • c++关于析构的那点小事(个人吐槽向

     1 #include<iostream>
     2 using namespace std;
     3 class test
     4 {
     5     int *i;
     6     
     7 public:
     8     test(int n) { i = new int[n];}
     9     void func(int n) { test a(n);  a.f(); cout << endl; }
    10     void f() { cout<<this<<endl; }
    11     void shit(test x) { x.i = i; }
    12     ~test() { cout << this << "被析构了" << endl; }
    13 };
    14 void main()
    15 {
    16     test b(3);
    17     cout << "b  "; b.f();
    18     cout << "b 中 a";b.func(5);
    19     test c(6);
    20     cout << "c  "; c.f();
    21     cout << "c 中 a"; c.func(5);
    22         b.shit(c);
    23 }

    可以看出,先析构被调用的成员函数语句块中定义的类,再析构类中成员函数声明时的实例形参。最后析构主函数中定义的实例。

    20160421 修改,成员函数不在类所占有的内存里,类的成员函数占有一片共有的内存段。关于形参为对象或者语句块中有类的成员,都是在调用到时才分配的内存

     1 #include<iostream>
     2 using namespace std;
     3 class test
     4 {
     5     int *i;
     6     
     7 public:
     8     test(int n) { i = new int[n];}
     9     void func(int n) { test a(n);  a.f(); cout << endl; }
    10     void f() { cout<<this<<endl; }
    11     void shit(test x) { x.i = i; }
    12     ~test() { cout << this << "被析构了" << endl; }
    13 };
    14 void main()
    15 {
    16     test b(3);
    17     cout << "b  "; b.f();
    18     //cout << "b 中 a";b.func(5);
    19     test c(6);
    20     cout << "c  "; c.f();
    21     //cout << "c 中 a"; c.func(5);
    22         b.shit(c);
    23 }

    面向过程中子函数无论是否被调用都是先通过声明么?类中的函数均在程序build时被声明(函数体内部的语句并没有build,调用时才会)。所以

    即使不调用类中除了构造和析构以外的成员函数。如果这些函数中有以类的对象为形参(非引用,引用不是对象)的成员函数,那么这个形参在??时被析构

  • 相关阅读:
    用Visual Studio2010 编译 C++文件"hello world”
    hdu 1010 Tempter of the Bone(dfs+奇偶剪枝)
    最长子串(动态规划)
    C++中,访问字符串的三种方法
    POJ3260:The Fewest Coins(混合背包)
    如何做好基层技术管理工作?
    UVa10651(记忆化搜索)
    <Win32_5>深入浅出Win32的计时器
    【转载】一步一步写算法(之hash表)
    C可变参数函数 实现
  • 原文地址:https://www.cnblogs.com/yuelien/p/5410661.html
Copyright © 2011-2022 走看看