析构的本质是什么??
析构某个对象后,只是告诉编译器这一块内存不再为某个对象独占了,你可以访问它,别的对象或者变量也可以访问它并使用该内存区域存储他们的数据,但是在他们使用之前,存放在该内存区域的数据并没有删除,此时用指针能访问里面的数据(前提是没有写入新的数据)。
以上理解正确不???
有代码为证:
#include<iostream>
using namespace std;
class A
{
public:
A(int i){x=i;cout<<"constructing"<<endl;}
A(A &a){this->x=a.x;cout<<"copying"<<endl;}
~A(){cout<<"destructing"<<endl;}
int get(){return x;}
private:
int x;
};
A func()
{
cout<<"func called"<<endl;
A a(23);
cout<<"the address of a "<<&a<<endl;
return a;
}
void main()
{
A *r=&func();
cout<<"the copy of a address "<<r<<endl;
cout<<r->get()<<endl;
}
输出结果:
输出结果中第二,三行的destructing 是不是代表析构局部对象a和临时对象(a的一个副本,调用函数func()后产生的),此时临时对象不是最后析构的?
如果是,r为什么还能访问该临时对象??
还有一说法,对临时对象的引用可以扩大该临时变量的生存期.
改成:#include<iostream>
using namespace std;
class A
{
public:
A(int i){x=i;cout<<"constructing"<<endl;}
A(A &a){this->x=a.x;cout<<"copying"<<endl;}
~A(){cout<<"destructing"<<endl;}
int get(){return x;}
private:
int x;
};
A func()
{
cout<<"func called"<<endl;
A a(23);
cout<<"the address of a "<<&a<<endl;
return a;
}
void main()
{
A &r=func();
cout<<"the copy of a address "<<&r<<endl;
cout<<r.get()<<endl;
}
输出结果中第一次析构局部变量a,最后析构临时变量(调用func()函数后产生的)!!
此时临时变量的生存期扩大了???
如果把此临时对象赋值给其他对象,该临时变量好像没有析构了?
代码:#include<iostream>
using namespace std;
class A
{
public:
A(int i){x=i;cout<<"constructing"<<endl;}
A(A &a){this->x=a.x;cout<<"copying"<<endl;}
~A(){cout<<"destructing"<<endl;}
int get(){return x;}
private:
int x;
};
A func()
{
cout<<"func called"<<endl;
A a(23);
cout<<"the address of a "<<&a<<endl;
return a;
}
void main()
{
A r=func();
cout<<"the copy of a address "<<&r<<endl;
cout<<r.get()<<endl;
}
输出结果中临时对象好像没有析构的,析构的应该是局部对象a和对象r(理论上是调用拷贝构造函数创建对象r,可是编译器给优化了)??
以上三个程序中的临时对象生存期为什么不同??
临时对象的生存期到底是怎样的??
还望各位详细解答,如果能解决困扰我已久的问题,鄙人感激不尽!!!