指向对象的指针向量 - 如何避免内存泄漏?

发布于 2024-09-13 20:13:38 字数 663 浏览 7 评论 0原文

我们通常如何处理其元素是指向对象的指针的向量?我的具体问题是下面提供的代码末尾的注释。谢谢。

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

  }

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

  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡忘如思 2024-09-20 20:13:38

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

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

或唯一指针向量 (C++0x)(如果对象实际上并未在此容器与其他对象之间共享

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

,或者使用 boost 指针容器

  boost::ptr_vector<A> l;

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

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!

寄意 2024-09-20 20:13:38

使用shared_ptr数组,或者类似的智能指针。请注意,您的基类必须有一个虚拟析构函数,此代码才能正常工作。

Use an array of shared_ptr, or similar smart pointer. And note that your base class must have a virtual destructor for this code to work correctly.

望她远 2024-09-20 20:13:38

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文