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

时间:2023-03-08 18:00:07
 #include<iostream>
using namespace std;
class test
{
int *i; public:
test(int n) { i = new int[n];}
void func(int n) { test a(n); a.f(); cout << endl; }
void f() { cout<<this<<endl; }
void shit(test x) { x.i = i; }
~test() { cout << this << "被析构了" << endl; }
};
void main()
{
test b();
cout << "b "; b.f();
cout << "b 中 a";b.func();
test c();
cout << "c "; c.f();
cout << "c 中 a"; c.func();
b.shit(c);
}

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

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

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

 #include<iostream>
using namespace std;
class test
{
int *i; public:
test(int n) { i = new int[n];}
void func(int n) { test a(n); a.f(); cout << endl; }
void f() { cout<<this<<endl; }
void shit(test x) { x.i = i; }
~test() { cout << this << "被析构了" << endl; }
};
void main()
{
test b();
cout << "b "; b.f();
//cout << "b 中 a";b.func(5);
test c();
cout << "c "; c.f();
//cout << "c 中 a"; c.func(5);
b.shit(c);
}

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

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

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