strcpy(p.f, "Computer");
cout << p.f << endl;
aa q(p);// 调用默认的拷贝构造函数
printf("q.f=%p\n",q.f);
cout << q.f << endl;
strcpy(p.f, "Software");
cout << p.f << endl;
cout << q.f << endl;
strcpy(q.f, "Software");
cout << p.f << endl;
cout << q.f << endl;
return 0;
}
运行结果:
调用构造函数
p.f=003F1048
Computer
q.f=003F1048
Computer
Software
Software
Software
Software
调用析构函数
调用析构函数
通过上面的例子,我们能清楚的看到,第二个对象调用拷贝构造函数,q.f获得的地址值与p.f相同,即指向了同一片内存区域。程序结束时,会两次调用析构函数,即同一个指针执行两遍delete操作,会发生什么呢?这可能是一场灾难,可能会破坏该堆及自由内存表。
那我们该如何避免呢?这里我们就需要使用深拷贝。
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version :
// Copyright : sg131971@qq.com
// Description : Hello World in C++, Ansi-style
//============================================================================
#include
#include
using namespace std;
class aa
{
public:
aa()
{
cout << "调用构造函数" << endl;
f = new char[10];
}
aa(aa const & s)
{
cout << "调用拷贝构造函数" << endl;
f = new char[10];
strcpy(f, s.f);
}
~aa()
{
cout << "调用析构函数" << endl;
delete[] f;
}
char * f;
};
int main(int argc, char **argv)
{
aa p;
printf("p.f=%p\n", p.f);
strcpy(p.f, "Computer");
cout << p.f << endl;
aa q(p);// 调用用 的拷贝构造函数
printf("q.f=%p\n", q.f);
cout << q.f << endl;
strcpy(p.f, "Software");
cout << p.f << endl;
cout << q.f << endl;
strcpy(q.f, "Software");
cout << p.f << endl;
cout << q.f << endl;
return 0;
}
运行结果:
调用构造函数
p.f=00351048
Computer
调用拷贝构造函数
q.f=00351060
Computer
Software
Computer
Software
Software
调用析构函数
调用析构函数
现在我们可以看到,p.f和q.f分别指向不同的内存区域。
作者 sg131971的学习笔记