Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete shared_ptr content and replace it with new object?

Tags:

c++

c++11

I wonder if there is a way to delete an object held by shared_ptr and create new one so all other copies of this shared_ptr would be still valid and point to this object?

like image 680
Bartek Boczar Avatar asked Feb 07 '16 19:02

Bartek Boczar


People also ask

Can you delete a shared_ptr?

[Edit: you can delete a shared_ptr if and only if it was created with new , same as any other type.

Can you convert shared_ptr to Unique_ptr?

In short, you can easily and efficiently convert a std::unique_ptr to std::shared_ptr but you cannot convert std::shared_ptr to std::unique_ptr .

Can shared_ptr be copied?

The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.

What happens when shared_ptr goes out of scope?

All the instances point to the same object, and share access to one "control block" that increments and decrements the reference count whenever a new shared_ptr is added, goes out of scope, or is reset. When the reference count reaches zero, the control block deletes the memory resource and itself.


1 Answers

You simply 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;
}
like image 68
WhiZTiM Avatar answered Oct 20 '22 01:10

WhiZTiM