2013-12-07 35 views
0

如果我有一个需要深度拷贝类的重载赋值操作符,我该如何去做呢? Person类包含一个名称类C++带有赋值运算符的类的深拷贝

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; 
} 
+0

首先,赋值和拷贝构造函数采用'const X&'而不仅仅是'X&'。其次,“name”的类型是什么? '姓名&?如果是,它将不起作用。如果不是,请不要使用'new'因为你有泄漏。 – Johan

+0

Uee复制和交换成语:http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom – Davidbrcz

回答

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