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 }

c++关于析构的那点小事(个人吐槽向

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

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 }

c++关于析构的那点小事(个人吐槽向

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

即使不调用类中除了构造和析构以外的成员函数。如果这些函数中有以类的对象为形参(非引用,引用不是对象)的成员函数,那么这个形参在??时被析构
原文链接: https://www.cnblogs.com/yuelien/p/5410661.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/232204

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午3:23
下一篇 2023年2月13日 下午3:23

相关推荐