如果类封装了原始指针,如下面这个类:
class MyString
{
private:
char* Buffer;
public:
// constructor
MyString(const char* InitialInput)
{
if(InitialInput != NULL)
{
Buffer = new char [strlen(InitialInput) + 1];
strcpy(Buffer, InitialInput);
}
else
Buffer = NULL;
}
}
如果没有实现赋值运算符,编译器提供默认的赋值运算符,但它只复制char*buff包含的地址,而不会复制指向内存中的内容,为了确保复制时进行深复制,应定义赋值运算符。具体如下:
MyString& operator= (const MyString& CopySource)
{
if ((this != &CopySource) && (CopySource.Buffer != NULL))
{
if (Buffer != NULL)
delete[] Buffer;
// ensure deep copy by first allocating own buffer
Buffer = new char [strlen(CopySource.Buffer) + 1];
// copy from the source into local buffer
strcpy(Buffer, CopySource.Buffer);
}
return *this;
}