简体   繁体   中英

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

If I had a overloaded assignment operator that need to deep-copy a class, how would I go about doing it? class Person contains a Name class

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);
}

in the name class copy-constructor and assignment operator

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

I would leverage the existing copy constructor, destructor, and added swap() function:

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

All copy assignments I'm implementing look like this implementation. The missing swap() function is also trivial to write:

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

Likewise for Person .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM