Does this leak?

Started by
4 comments, last by Zakwayda 14 years, 6 months ago
What is the proper way to make a vector of an abstract class type with polymorphism? This is the best I could come up with, but I can't help getting the feeling that it is leaking somewhere.

#ifndef SHAREDPOINTER_VECTOR_H
#define SHAREDPOINTER_VECTOR_H

#include "BOOST/shared_ptr.hpp"
#include <cassert>

template <class T>
void AddSmartPointerToVector( std::vector<boost::shared_ptr<T> >& avector, T* aobject)
{
    assert( aobject != NULL);

    boost::shared_ptr<T> newsharedptr(aobject);
    avector.push_back(newsharedptr);
}

#endif


    AddSmartPointerToVector<Brush>( mybrushes, new MultiBlock(0,0,10,1));
    AddSmartPointerToVector<Brush>( mybrushes, new MultiBlock(0,288,10,1));
    AddSmartPointerToVector<Brush>( mybrushes, new MultiBlock(0,32,1,8));
    AddSmartPointerToVector<Brush>( mybrushes, new MultiBlock(288,32,1,8));

I trust exceptions about as far as I can throw them.
Advertisement
No, that doesn't leak. By creating a shared_ptr from a raw pointer, the shared_ptr takes ownership of the raw pointer. The shared_ptr will then delete the raw pointer for you, when the shared_ptr is destroyed.
Ideally, you would pass a shared_ptr, rather than a raw pointer. This makes the ownership semantics explicit. You might want to look at boost::make_shared<>() to remove some of the verbosity.
When I use push_back, does that copy the smart pointer?
I trust exceptions about as far as I can throw them.
Yes. The smart pointer object is copied, but there is no copy of the pointee involved.
Quote:When I use push_back, does that copy the smart pointer?
Yes, a copy of the smart pointer is made in this case. (The object that the smart pointer references, however, is not copied.)

This topic is closed to new replies.

Advertisement