2013-12-07 38 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