简体   繁体   中英

C++ (Logical Copy Constructor) How do I copy an object?

I have a class:

class Person{
public:
    Person();
    ~Person();
    string name;
    int* age;
};

int main()
{
    Person* personOne = new Person;
    personOne->name = "Foo";
    personOne->age = new int(10);


    return 0;
}

How do I create another object of Person that copies all of personOne data? The age pointer needs to be pointing to a new int so whenever the age changes in personOne or personTwo, it doesn't affect each other.

There are two posibilites:

  • copy constructor + assignment operator
  • clone method

Code:

class Person{
public:
    Person();
    ~Person();
    Person (const Person& other) : name(other.name), age(new int(*(other.age)))
    {
    }
    Person& operator = (const Person& other)
    {
        name = other.name;
        delete age; //in case it was already allocated
        age = new int(*(other.age))
        return *this;
    }
    //alternatively 
    Person clone()
    {
        Person p;
        p.name = name;
        p.age = new int(age);
        return p;
    }

    string name;
    int* age;
};

Answer these before going forward:

  • do you really need an int pointer?
  • are you aware of smart pointers?
  • do you free all memory you allocate?
  • do you initialize all members in the constructor?

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