C++ 三大函数该写就要写
记得C++ 沉思录上说过,如果数据成员有指针类型的,最好把三大函数补全,不然的话容易产生浅拷贝和内存泄露。这里给出一个简单的例子。
#include <iostream> #include <vector> #include <algorithm> #include <cstring> using namespace std; class CDemo { public: CDemo():str(new char[1]) { str[0] = '\0'; cout<< "Construct"<<endl; }; CDemo(const char *s) : str(new char[strlen(s) + 1]) { strcpy(str,s); } CDemo( const CDemo & D) : str(new char [strlen(D.c_str()) + 1]) { strcpy(str,D.c_str()); } ~CDemo() { if(str != NULL) { delete [] str; str = nullptr; cout<< "Deconstruct!"<<endl; } cout<< "Deconstruct finish"<<endl; } CDemo & operator = ( CDemo CD) { swap(str, CD.str); return * this; } char *c_str() const { return str; } private: char *str; }; int main() { CDemo d1("trend micro"); CDemo d2; d2 = d1; vector<CDemo> * a1 = new vector<CDemo>(); a1->push_back(d1); cout<< "d1: "<<d1.c_str()<<endl; cout<< "a1: "<<a1->front().c_str()<<endl; strcpy(a1->front().c_str(), "change"); //如果没有拷贝构造函数,则这里会出错 cout<<a1->front().c_str()<<endl; delete a1; //如果不定义拷贝构造函数将出现push_back的时候的浅拷贝情况,析构a1的时候要 //delete 类中的str,导致str被delete两次 return 0; }
make it simple, make it happen