How to delete the contents of shared_ptr and replace it with a new object?

I wonder if there is a way to delete the object stored in shared_ptr and create a new one so that all other copies of this shared_ptr are still valid and point to this object?

+4
source share
1 answer

You just reassign or reset it.

Example:

#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;
}
+3
source

Source: https://habr.com/ru/post/1627684/


All Articles