带有赋值运算符的类的C++深度复制

C++ Deep-copy of a class with assignment operator

本文关键字:深度 复制 C++ 赋值运算符      更新时间:2023-10-16

如果我有一个重载的赋值运算符,需要深度复制一个类,我该怎么做?类Person包含一个Name类

Person& Person::operator=(Person& per){
if (this==&per){return *this;}
// my attempt at making a deep-copy but it crashes  
this->name = *new Name(per.name);
}

在名称类中复制构造函数和赋值运算符

Name::Name(Name& name){
if(name.firstName){
firstName = new char [strlen(name.firstName)+1];
strcpy(firstName,name.firstName);
}
Name& Name::operator=(Name& newName){
if(this==&newName){return *this;}
if(newName.firstName){
firstName = new char [strlen(newName.firstName)+1];
strcpy(firstName,newName.firstName);
return *this;
}

我将利用现有的复制构造函数、析构函数和添加的swap()函数:

Name& Name::operator= (Name other) {
    this->swap(other);
    return *this;
}

我正在执行的所有复制作业看起来都像这个实现。缺少的swap()函数对编写来说也是微不足道的:

void Name::swap(Name& other) {
    std::swap(this->firstName, other.firstName);
}

对于CCD_ 3也是如此。