Search code examples
c++boostshared-ptr

shared_ptr and reference counter


In this example I took from the book "Beyond the C++ Standard Library - An introduction to Boost" :

boost::shared_ptr<A> createA()
{
boost::shared_ptr<A> p(new B()); // B is a class
return p;
}
int main()
{
typedef std::vector<boost::shared_ptr<A> > container_type;
container.push_back(createA()); /* before returning p does the reference count reach 2 ? */
assert(container[0].use_count() == 1); // true
}

I want to know if the reference counter inside "p" can reach a maximum of 2 : 1 when we create the shared pointer "p" and 2 before destroying "p" after returning (copying) its value...

The goal of my question is to know which option is better when we have a function that returns a shared_ptr : returning a shared_ptr object or a reference to a dynamically created shared_ptr. After testing this :

boost::shared_ptr<A>& createA()
{
boost::shared_ptr<A> &p = *(new boost::shared_ptr<A>(new B));
assert(p.use_count() == 1);
return p;
}
/* ... */
boost::shared_ptr<A> & tmp_ref = createA();
assert(tmp_ref.use_count() == 1);
container.push_back(tmp_ref);
assert(container[0].use_count() == 2);

I can say that returning an object is preferable because in the other case the ref count is 2 and that's logic (1 because we created the shared_ptr dynamiccaly and 2 because the vector has copied it).


Solution

  • Yes, it could reach 2.

    It could reach higher than 2 because we don't know how many copies the vector implementation may make internally as it's pushing back. It's allowed to copy as many times as it wants.