上代码,定义类:
// helloworld.h
{
public:
explicit HelloWorld();
HelloWorld(const HelloWorld &otherHW);
void operator =(const HelloWorld &hw);
~HelloWorld();
int *getPtr() const;
private:
int *m_ptr;
};
// helloworld.cpp
HelloWorld::HelloWorld()
{
m_ptr = new int(100);
}
HelloWorld::HelloWorld(const HelloWorld &otherHW)
{
m_ptr = otherHW.getPtr();
}
void HelloWorld::operator =(const HelloWorld &hw)
{
m_ptr = hw.getPtr();
}
HelloWorld::~HelloWorld()
{
delete m_ptr;
}
int *HelloWorld::getPtr() const
{
return m_ptr;
}
调用代码:
int main() {
HelloWorld hw1;
HelloWorld hw2;
cout<<"hw1"<<hw1.getPtr()<<endl;
cout<<"hw2"<<hw2.getPtr()<<endl;
return 0;
}
输出:
hw1 0x7ffea3c02b10
hw2 0x7ffea3c02b20
假设存在拷贝赋值,即:
hw1 = hw2;
cout<<"hw1\t"<<hw1.getPtr()<<endl;
cout<<"hw2\t"<<hw2.getPtr()<<endl;
程序会发生奔溃,因为在operator =(const HelloWorld &hw)发生了浅拷贝m_ptr = hw.getPtr(),而HelloWorld的析构函数会delete m_ptr,因此在发生了拷贝赋值之后,两个对象的m_ptr指向了同一个内存区域,调用两次析构会删除m_ptr两次,因此造成程序奔溃。
解决方法可以如下:
void HelloWorld::operator =(const HelloWorld &hw)
{
// m_ptr = hw.getPtr(); // error
memcpy(m_ptr, hw.getPtr(), sizeof(int)); // ok
}