In this example I took from the book "Beyond the C++ Standard Library - An introduction to Boost" :
boost::shared_ptr<A> p(new B()); // B is a class
typedef std::vector<boost::shared_ptr<A> > container_type;
container.push_back(createA()); /* before returning p does the reference count reach 2 ? */
assert(container.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> &p = *(new boost::shared_ptr<A>(new B));
assert(p.use_count() == 1);
/* ... */
boost::shared_ptr<A> & tmp_ref = createA();
assert(tmp_ref.use_count() == 1);
assert(container.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).
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.
Your second example has a memory leak, so you do not compare apples to apples. Anyway it is definitely cheaper to increase counter rather than create another object on a heap. I do not quite understand why you care about reference counter so much and make decision based if it reaches certain value. Do you understand that if counter reaches 2 it does not make another copy of object 'A'?
Note: for C++11 your function
createA() should return
std::unique_ptr instead, which is more effective than
std::shared_ptr and could be converted to shared if necessary.