当类的数据成员存在指针变量,并且被指对象通过某些成员函数(如构造函数)分配地址,那么默认的默认析构、拷贝构造、operator=通常不可用。若使用默认函数,被复制的是指针,而不是指针所指向的对象(复制之后,两个指针指向同一对象)。另一个问题是可能造成内存泄露。
内存泄漏例子
假设A类只有默认析构、拷贝构造、operator=函数,但含一个指针变量。下面这种情况,a的指针变量被初始化,并指向某一地址1。b的指针变量也被初始化,并指向某一地址2。
但b=a;默认拷贝构造把a的指针变量的值复制给b的指针变量,故a、b的的指针变量均指向同一块地址1。而地址2所在变量依然存在,无法释放,因为已经没有指针存储这个地址了。
A a(0);
A b;
b=a;
当类的数据成员存在指针变量,需要考虑改变/增加析构、拷贝构造、operator=函数
//IntCell.h
#ifndef IntCell_H
#define IntCell_H
class IntCell
{
public:
explicit IntCell(int initialValue=0);
IntCell(const IntCell &rhs);
~IntCell();
const IntCell & operator=(const IntCell& rhs);
int read()const;
void write(int x);
private:
int *storeValue;
};
#endif
//IntCell.cpp
#include"IntCell.h"
IntCell::IntCell(int initialValue)
{
storeValue = new int (initialValue);
}
IntCell::IntCell(const IntCell& rhs)
{
storeValue = new int(*rhs.storeValue);
}
IntCell::~IntCell()
{
delete storeValue;
}
const IntCell& IntCell::operator=(const IntCell & rhs)
{
if (this!=&rhs)
{
*storeValue = *rhs.storeValue;
}
return *this;
}
int IntCell::read ()const
{
return *storeValue;
}
void IntCell::write(int x)
{
*storeValue = x;
}