Object pointer vector - how to avoid memory leak?

How do we deal with a vector whose elements are pointers to an object? My specific question is the comment at the end of the code below. Thank.

class A
{
 public:
 virtual int play() = 0 ; 
};

class B : public A 
{
public:
 int play() {cout << "play in B " << endl;};

};

class C : public A 
{
public:
 int play() {cout << "play in C " << endl;};

};


int main()
{

    vector<A *> l;
    l.push_back(new B());
    l.push_back(new C());

    for(int i = 0 ; i < l.size();i++)
    {
            l[i]->play();
    }

    //Do i have to do this to avoid memory leak? It is akward. Any better way to do this? 
    for(int i = 0 ; i < l.size();i++)
    {
            delete l[i];
    }

  }
0
source share
3 answers

Yes, you must do this to avoid memory leaks. The best ways to do this is to create a vector of common pointers ( boost , C ++ TR1, C ++ 0x,)

 std::vector<std::tr1::shared_ptr<A> > l;

or a vector of unique pointers (C ++ 0x), if the objects are not actually divided between this container and something else

 std::vector<std::unique_ptr<A>> l;

or use boost pointer containers

  boost::ptr_vector<A> l;

PS: Do not forget the virtual destructor, like @Neil Butterworth!

+7
source

shared_ptr . , , .

+5

The best way would be to use smart pointers ( Boost shared_ptr ) to avoid this kind of thing. But if you NEED to have source pointers, I think this is the way to do it.

0
source

All Articles