copy构造函数的秘密

1.先来看这段代码:

MyString::MyString()
{
this->mstr = NULL;
}

MyString::MyString(MyString &str)
{
//用一个对象去初始化另一个对象
this->mstr = new char(strlen(str.mstr) + 1);
strcpy(this->mstr, str.mstr);
}

MyString::~MyString()
{
//if (this->mstr != NULL)
//{
// delete[] this->mstr;
//}
//this->mstr = NULL;
}

 

MyString& MyString::operator=(MyString &str)
{
/*if (this->mstr != NULL)
{
delete[] this->mstr;
}*/
this->mstr = new char(strlen(str.mstr) + 1);
strcpy(this->mstr, str.mstr);
return *this;
}

MyString MyString::operator+(MyString &str)
{
MyString mString;
mString.mstr = new char(strlen(this->mstr) + strlen(str.mstr) + 1);
strcpy(mString.mstr, this->mstr);
strcat(mString.mstr, str.mstr);
return mString;
}

void main()

{

...

str4 = str3 + str5;

getchar();

}

 内容说明: 在”+“重载return的时候会出现一次匿名对象的创建和销毁,调用了copy构造函数来初始化这个匿名对象并且还会被析构释放。

posted @ 2014-11-15 14:13  soft.push("zzq")  Views(225)  Comments(0Edit  收藏  举报