c++ - 复制并修改一个shared_ptr

标签 c++

我想知道如何“复制”一个 shared_ptr 并修改其内容。

在下面的示例中,创建了一个“模板人”,我想将其用作每个人都会从中复制的“人”。但是,当 std::shared_ptr p2 被分配给 template_person 时,p2 中的每个修改也会影响 template_person。有没有办法避免这种情况,或者我应该使用普通指针?

这是我的第一种方法。我想这样做是为了消耗更少的内存。

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

最佳答案

使用复制构造函数:

auto p2 = std::make_shared<Person>(*template_person);

关于c++ - 复制并修改一个shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50600316/

相关文章:

c++ - 使用 streamhtmlparser 的例子

C++ 错误 : no matching function for all to

c++ - 在 C++ 应用程序中嵌入用户名以使登录更容易?

c++ - 在 Linux 上寻找静态链接排序工具

c++ - 针对编译时常量优化的函数

c++ - std::thread 构造函数中的可移动参数 (Visual C++ 2012)

C++ 继承 - 无法在 cpp 文件中定义方法

c++ - 为不可复制对象选择构造函数

c++ - 为什么C/C++会自动将char/wchar_t/short/bool/enum类型转换为int?

c++ - 写入具有 map 容器内容的文件 C++