如果不主动编写拷贝函数和赋值函数,编译器将以"位拷贝"的方式自动生成缺省的函数,如果类中含有指针变量,那么这两个缺省函数中就隐含了错误,会造成严重后果.
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Demo
{
int l;
public:
char *p;
Demo(const char *s)
{
l = strlen(s);
p = new char [l + 1];
strcpy(p, s);
}
Demo()
{
p = new char[8];
cout<<"*****/n";
}
void show()
{
cout<<&l<<" "<<(int)&p[0]<<" "<<p<<endl;
}
~Demo()
{
delete p;
}
};
int main(int argc, char *argv[])
{
Demo h("first");
Demo r = h;
r.show();
h.show();
system("PAUSE");
return EXIT_SUCCESS;
}
运行结果为: 0x22ff40 4013512 first 0x22ff50 4013512 first 可以看出h和r中的p指向是一样的,那么在修改一个的时候也会修改另一个,另一个严重问题是在析构时,会对同一块内存释放两次. 解决办法是对拷贝函数和赋值函数显式声明定义或者将这两个函数做为类的私有函数进行声明.可以防止用户的误用.