#include <iostream>
using namespace std;
class Test
{
public:
explicit Test( int init = 0 )
{
pStore = new int(init);
}
int read() const
{
return *pStore;
}
void write(int x)
{
*pStore = x;
}
private:
int *pStore;
};
int main()
{
Test test1(2);
Test test2 = test1;
Test test3;
test3 = test2;
test1.write(4);
cout << test1.read() << endl
<< test2.read() << endl
<< test3.read() << endl;
return 0;
}
输出:
4
4
4
由于使用默认的拷贝构造函数和赋值运算符,输出结果不为想象中的4,2,2。
程序存在的问题:
浅复制:指针被复制而不是指针所指的内容被复制
在 test3 = test2 之前:
test1.pStore == test2.pStore
test3 = test2 后
test1.pStore == test2.pStore == test3.pStore
内存泄露:test1 与 test3分配的内存都没有得到释放
解决方法:添加三个函数
~ Test()
{
delete pStore;
}
const Test & operator=( const Test & rtest )
{
if ( this != &rtest )
*pStore = *rtest.pStore;
return *this;
}
Test( const Test &rtest)
{
pStore = new int(*rtest.pStore);
}