如何删除shared_ptr内容并将其替换为新对象?

时间:2016-02-07 19:40:02

标签: c++ c++11

我想知道是否有办法删除shared_ptr持有的对象并创建新对象,这样shared_ptr的所有其他副本仍然有效并指向此对象?

1 个答案:

答案 0 :(得分:5)

您只需reassignreset

示例:

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