关于C++中深层复制的问题
#include "iostream"
using namespace std;
class A
{
public:
A()
{
x=new int;
*x=5;
cout<<"执行构造函数……\n";
}
A(A&a)
{
x=new int;
*x=*(a.x);
cout<<"复制函数执行……\n";
}
~A()
{
delete x;
cout<<"析构函数执行中……\n";
}
int Print()const
{
return *x;
}
void set(int i)
{
*x=i;
}
private:
int *x;
};
void main ()
{
A *p=new A;
cout<<p->Print()<<endl;
A b=*p;
cout<<b.Print()<<endl;
p->set(99);
cout<<p->Print()<<endl;
return;
}
在这段代码中,我没加上delete p;这条语句,它就只调用了析构函数来析构了对象b,如果我加上delete p;则会调用析构函数2次来分别析构对象p和对象b,我想问的是,析构函数不是在主函数返回前被自动调用来析构所有的对象么?为什么我不加delete p,它就不析构对象p,而只析构对象b呢?