龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C++中复制构造函数和重载赋值操作符总结(2)

时间:2014-10-10 03:06来源:网络整理 作者:网络 点击:
分享到:
在代码中都加入了注释,这里就不再做详细的说明了。再次总结一下,如果对象在声明的同时将另一个已存在的对象赋给它,就会调用复制构造函数;如果

在代码中都加入了注释,这里就不再做详细的说明了。再次总结一下,如果对象在声明的同时将另一个已存在的对象赋给它,就会调用复制构造函数;如果对象已经存在了,然后再将另一个已存在的对象赋给它,调用的就是重载赋值运算符了。这条规则很适用,希望大家能记住。

复制构造函数和重载赋值操作符的实现要点

在一般的情况下,编译器给我们生成的默认的复制构造函数和重载赋值操作符就已经够用了;但是在一些特别的时候,需要我们手动去实现自己的复制构造函数。

我们都知道,默认的复制构造函数和赋值运算符进行的都是”shallow copy”,只是简单地复制字段,因此如果对象中含有动态分配的内存,就需要我们自己重写复制构造函数或者重载赋值运算符来实现”deep copy”,确保数据的完整性和安全性。这也就是大家常常说的深拷贝与浅拷贝的问题。下面我就提供一个比较简单的例子来说明一下:

复制代码 代码如下:

#include <iostream>
using namespace std;
 
const int MAXSIZE = 260;
 
class CTest
{
public:
     CTest(wchar_t *pInitValue)
     {
          // Here, I malloc the memory
          pValue = new wchar_t[MAXSIZE];
          memset(pValue, 0, sizeof(wchar_t) * MAXSIZE);
          wcscpy_s(pValue, MAXSIZE, pInitValue);
     }
 
     ~CTest()
     {
          if (pValue)
          {
               delete[] pValue; //finalseabiscuit指出,谢谢。2014.7.24
               pValue = NULL;
          }
     }
 
     CTest(const CTest &test)
     {
          // Malloc the new memory for the pValue
          pValue = new wchar_t[MAXSIZE];
          memset(pValue, 0, sizeof(wchar_t) * MAXSIZE);
          wcscpy_s(pValue, MAXSIZE, test.pValue);
     }
 
     CTest& operator=(const CTest &test)
     {
          // This is very important, please remember
          if (this == &test)
          {
               return *this;
          }
 
          // Please delete the memory, this maybe cause the memory leak
          if (pValue)
          {
               delete[] pValue; // 方恒刚指出的问题。非常感谢 2014.3.15
          }
 
          // Malloc the new memory for the pValue
          pValue = new wchar_t[MAXSIZE];
          memset(pValue, 0, sizeof(wchar_t) * MAXSIZE);
          wcscpy_s(pValue, MAXSIZE, test.pValue);
          return *this;
     }
 
     void Print()
     {
          wcout<<pValue<<endl;
     }
 
private:
     wchar_t *pValue; // The pointer points the memory
};
 
int main()
{
     CTest obj(L"obj");
     obj.Print();
 
     CTest obj2(L"obj2");
     obj2.Print();
     obj2 = obj;
     obj2.Print();
 
     obj2 = obj2;
     obj2.Print();
 
     return 0;
}

精彩图集

赞助商链接