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?
[Edit: you can delete a shared_ptr if and only if it was created with new , same as any other type.
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 .
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With