mercredi 30 mai 2018

c++1y copy and modify a shared_ptr

I would like to know how to "copy" a shared_ptr and modify the contents.

In the following example a "template person" is created and I would like to use it as a "Person" that every body would copy from it. However when std::shared_ptr p2 is assigned the template_person every modification in p2 impacts template_person as well. Is there a way to avoid this, or should I use a normal pointer?

#include <iostream>
#include <memory>
#include <string>

class Person{
public:
    ~Person() {}
    Person(int a, std::string b) : age_(a), name_(b) {}

    void set_age(int x) { age_ = x; }
    int age() { return age_; }

private:
    int age_;
    std::string name_;
};

int main () {

    std::shared_ptr<Person> template_person = std::make_shared<Person>(10, "test");

    std::shared_ptr<Person> p2 = template_person;

    p2->set_age(20);

    std::cout << p2->age() << " " << template_person->age() << std::endl;
    //prints 20 20

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire