Does using .reset() on a std::shared_ptr delete all instances
When you use .reset()
, you are eliminating one owner of the pointer, but all of the other owners are still around. Here is an example:
#include <memory>
#include <cstdio>
class Test { public: ~Test() { std::puts("Test destroyed."); } };
int main()
{
std::shared_ptr<Test> p = std::make_shared<Test>();
std::shared_ptr<Test> q = p;
std::puts("p.reset()...");
p.reset();
std::puts("q.reset()...");
q.reset();
std::puts("done");
return 0;
}
The program output:
p.reset()... q.reset()... Test destroyed. done
Note that p
and q
are both owners of the object, and once both p
and q
are reset, then the instance is destroyed.
No.
The whole purpose of shared_ptr
is that you cannot delete it from one place if someone is using it in another. shared_ptr::reset()
just decreases use_count
by one and replaces its object by nullptr
.
The .reset() method only applies to the object it's called upon.
It just replaces the pointer that variable is holding.