Jump to content
  • Advertisement
Sign in to follow this  
Storyyeller

Does this leak?

This topic is 3177 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!