Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using .reset() on a std::shared_ptr delete all instances

I'm new to shared_ptr's and I'm trying to figure out the exact functionality of the .reset() function.

#include <memory> #include <stdio>  using namespace std; class SomeClass{};  int main()  {    shared_ptr<SomeClass> sp (nullptr);     //do some stuff, sp now has 10 co-owners     cout << sp.use_count << endl;    sp.reset();    cout << sp.use_count << endl;    return 0; } 

Would output

10 0 

So since I used the reset function are all instances deleted from memory? As in, have I just eliminated any possible memory leaks with sp? Obviously this was a toy example that I quickly made up, sorry if it has any errors.

Follow up situation:

shared_ptr<SomeClass> returnThis() {     shared_ptr<SomeClass> someObject(new SomeClass(/*default constructor for example*/) );     return someObject; } 

somehere in main:

shared_ptr<SomeClass> mainObject; mainObject = returnThis(); 

Does mainObject have a use count of 2 because someObject was created in a function but never cleared? Or is it one and the clean-up is done automatically when returning the value?

like image 762
zeus_masta_funk Avatar asked Feb 05 '14 22:02

zeus_masta_funk


People also ask

What happens when you reset a shared pointer?

std::shared_ptr<T>::reset. Replaces the managed object with an object pointed to by ptr . Optional deleter d can be supplied, which is later used to destroy the new object when no shared_ptr objects own it. By default, delete expression is used as deleter.

Does shared_ptr delete?

If you've allocated a shared_ptr dynamically then you're certainly allowed to delete it whenever you want.

What does shared_ptr get () do?

A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.


1 Answers

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.

like image 77
Dietrich Epp Avatar answered Oct 08 '22 19:10

Dietrich Epp