2

I wanted to know what .reset() does to a shared pointer. Does it simply decrement the reference count of a shared pointer by one as mentioned here or does it remove all reference counts to an object resetting the count to 0

This is my code sample here

std::vector<boost::shared_ptr<foo>> vec;
boost::shared_ptr<foo> f(boost::make_shared<foo>()); //ref count 1
vec.push_back(f); //ref count 1
vec.push_back(f); //ref count 3
int a = f.use_count(); //Will return 3
f.reset();        //Will turn the refernece count to 0
vec[1].reset();   //Will reduce the reference count by 1.
a = f.use_count();

I am curious as to why doing f.reset() turns the reference count to 0 while vec[1].reset() reduces the reference count by 1

Community
  • 1
  • 1
MistyD
  • 16,373
  • 40
  • 138
  • 240

1 Answers1

6

It releases the current reference. Other references are not affected.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • @MistyD After you call `f.reset()`, _of course_ `f.use_count()` is 0. It has no reference to anything! But if you call `vec[0].use_count()`, it should have the correct number. – C. K. Young Nov 23 '14 at 01:53