我想知道是否有办法删除shared_ptr持有的对象并创建新对象,这样shared_ptr的所有其他副本仍然有效并指向此对象?
答案 0 :(得分:5)
示例:
#include <iostream>
#include <memory>
template<typename T>
std::shared_ptr<T> func(std::shared_ptr<T> m)
{
m = std::make_shared<T>(T{});
//m.reset();
//m.reset(new int(56));
return m;
}
int main(){
std::shared_ptr<int> sp1 = std::make_shared<int>(44);
auto sp2 = func(sp1);
//sp1 is still valid after its copy was altered in func
std::cout << *sp1 << '\n' << *sp2 << std::endl;
}