向量对象的指针 - 如何避免内存泄漏? [英] vector of pointer to object - how to avoid memory leak?

查看:148
本文介绍了向量对象的指针 - 如何避免内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用一个向量,它的元素是对象的指针?我的具体问题是在下面提供的代码的结尾的注释。感谢。

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

  }


推荐答案

是的,你必须这样做,以避免内存泄漏。更好的方法是创建一个共享指针向量( boost ,C ++ TR1,C ++ 0x,)

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;

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

或使用boost 指针容器

  boost::ptr_vector<A> l;

PS:不要忘记A的虚拟析构函数,根据@Neil Butterworth!

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

这篇关于向量对象的指针 - 如何避免内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆