Search code examples
c++pointersboostshared-ptrptr-vector

boost::shared_ptr semantics (copying)


I just wanted to have a fresh pair of eyes that the below code is correct in that:

The pointers contained in the object trifoo (stored in a ptr_vector) are the shared pointers f, g, h.

Also, what is the result of the shared_ptr copy in the constructor of trifoo; is this the correct method of 'sharing' shared_ptr, ensuring reference counts are increased etc. All my other doubts I was able to test to verify, but I'm not sure how I can check this (properly). Any critique is welcome also.

#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>

class foo {
    int a, b;
public:
    foo(int A, int B) : a(A), b(B) {}
};

typedef boost::shared_ptr<foo> foo_ptr;

class trifoo {
    foo_ptr c, d, e;
public:
    trifoo(const foo_ptr& C, const foo_ptr& D, const foo_ptr& E) : c(C), d(D), e(E) {}
};

int main() {
    for (int i = 0; i < 5000000; i++) {
        foo_ptr f(new foo(1,2));
        foo_ptr g(new foo(2,3));
        foo_ptr h(new foo(4,5));

        boost::ptr_vector<trifoo> tris;

        tris.push_back(new trifoo(f, g, h));
    }

    return 0;
}

Note: the pointless loop was to test memory leaks, of which none occurred.


Solution

  • The code seems to be technically correct.

    Semantics of copying a shared_ptr, however it is done, is that the reference count of the referred-to object is increased. It just works. Nothing to worry about.

    Some style issues, though:

    • Passing shared_ptr by reference, or declaring it const, is meaningless. That's because it can always be copied. Just pass those shared_ptr's by value.

    • Use constructor initializer lists instead of assignments where practically possible.

    • Having the three new's in different expressions is very good. It avoids an exception safety pitfall. But even better, put that creation logic in a factory function.

    Cheers & hth.,