/*深拷贝用来解决浅拷贝造成的两次析构问题,因为浅拷贝时,两个指针指向同一块内存空间,析构时,一块内存空间释放两次,系统会报错。因此,我们需要重新开辟一块内存空间,使两个指针指向不同的空间,以此来解决问题。下面用一个String的例子来验证深拷贝。*/
#include <iostream>
#include <cstring>
class String
{
public:
String(const char *s = " ") : mPstr(new char[strlen(s) + 1]) //利用列表初始化为mPstr在堆上创建一个内存空间
{
strcpy(mPstr,s);
}
String(const String &other) : mPstr(new char[strlen(other.mPstr) + 1])
{
strcpy(mPstr, other.mPstr);
}
~String()
{
delete []mPstr;
}
void show() const
{
cout << mPstr << endl;
}
void append(const String &other) //实现一个追加功能
{
char *p = new char[strlen(this->mPstr) + strlen(other.mPstr) + 1];
strcpy(p, this->mPstr);
strcat(p, other.mPstr);
delete []this->mPstr;
mPstr = p;
//因为p是局部变量,所以不需要手动销毁
}
void assign(const String &other) //实现一个覆盖功能
{
if(this != &other) //如果覆盖的字符是本身,就不覆盖
{
char *p = new char[strlen(other.mPstr) + 1];
strcpy(p, other.mPstr);
delete []this->mPstr;
mPstr = p;
}
}
private:
char *mPstr;
};
int main(void)
{
String s1("Hello");
s1.show();
String s2("World");
s2.show();
s1.append(s2);
s1.show();
s1.assign(s2);
s1.show();
}
原文:https://www.cnblogs.com/wsl540/p/13747277.html