
代码:
#include <iostream>
#include <cstring> using namespace std; class mystring{
public:
mystring(string s){
cout<<"Constructor called."<<endl;
ptr = new char[s.length()+];
strcpy(ptr,s.c_str());
}
~mystring(){
cout<<"Destructor called.---"<<ptr<<endl;
delete ptr;
}
mystring &operator=(const mystring&);
private:
char* ptr;
}; mystring& mystring::operator=(const mystring& s){
if(this == &s) return *this;
cout<<this<<" "<<sizeof(this)<<endl;
delete ptr;
ptr = new char[strlen(s.ptr)+];
strcpy(ptr,s.ptr);
return *this;
} int main(){
mystring p1("hello");
mystring p2("OK");
p1 = p2; return ;
}
输出:
Constructor called.
Constructor called.
0x7ffeb8555900 8
Destructor called.---OK
Destructor called.---OK
分析:
显式定义赋值运算符重载函数,在复制时释放动态分配的内存空间并重新分配新的空间。假如没有重载赋值运算符,p1和p2指向同一块内存空间,程序结束时会导致对同一块内存空间的两次释放,这是不允许的。详见《C++面向对象程序设计教程》(第三版) 5.2.6节