如果我有一个重载的赋值运算符需要深层复制一个类,我该怎么做呢? class 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);
}
在名称类copy-constructor和赋值运算符
中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;
}
答案 0 :(得分:1)
我会利用现有的复制构造函数,析构函数和添加的swap()
函数:
Name& Name::operator= (Name other) {
this->swap(other);
return *this;
}
我正在实施的所有副本分配看起来像这个实现。缺少的swap()
函数写起来也很简单:
void Name::swap(Name& other) {
std::swap(this->firstName, other.firstName);
}
同样适用于Person
。