问题描述:

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).

网友答案:

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.

相关阅读:
Top