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,调用时才会)。所以

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

转载于:https://www.cnblogs.com/yuelien/p/5410661.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值