是否可以替换shared_ptr的多个实例引用的对象? 也许我不是很清楚,所以我举一个例子:
shared_ptr<Base> a = new Derived1();
auto b = a;
auto c = b;
// This function replaces the object where a, b, and c point to.
magic(a, new Derived2());
我已经查看了shared_ptr(重置和交换)的成员函数而没有运气。
答案 0 :(得分:3)
添加一个额外的间接层:
shared_ptr<unique_ptr<Base>> a = unique_ptr<Base>(new Derived1());
auto b = a;
auto c = b;
// This modifies the `unique_ptr` that `a` `b` and `c` point to
// to point to a new Derived2.
*a = unique_ptr<Base>(new Derived2());