标签:
代码:
1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 6 class mystring{ 7 public: 8 mystring(string s){ 9 cout<<"Constructor called."<<endl; 10 ptr = new char[s.length()+1]; 11 strcpy(ptr,s.c_str()); 12 } 13 ~mystring(){ 14 cout<<"Destructor called.---"<<ptr<<endl; 15 delete ptr; 16 } 17 mystring &operator=(const mystring&); 18 private: 19 char* ptr; 20 }; 21 22 mystring& mystring::operator=(const mystring& s){ 23 if(this == &s) return *this; 24 cout<<this<<" "<<sizeof(this)<<endl; 25 delete ptr; 26 ptr = new char[strlen(s.ptr)+1]; 27 strcpy(ptr,s.ptr); 28 return *this; 29 } 30 31 int main(){ 32 mystring p1("hello"); 33 mystring p2("OK"); 34 p1 = p2; 35 36 return 0; 37 }
输出:
Constructor called. Constructor called. 0x7ffeb8555900 8 Destructor called.---OK Destructor called.---OK
分析:
显式定义赋值运算符重载函数,在复制时释放动态分配的内存空间并重新分配新的空间。假如没有重载赋值运算符,p1和p2指向同一块内存空间,程序结束时会导致对同一块内存空间的两次释放,这是不允许的。详见《C++面向对象程序设计教程》(第三版) 5.2.6节
标签:
原文地址:http://www.cnblogs.com/hu983/p/5410514.html