Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

c++ - vector of pointer to object - how to avoid memory leak?

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

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];
    }

  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you have to do that to avoid memory leak. The better ways to do that are to make a vector of shared pointers (boost, C++TR1, C++0x, )

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

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

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

or use boost pointer containers

  boost::ptr_vector<A> l;

PS: Don't forget A's virtual destructor, as per @Neil Butterworth!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...