清除指针向量 [英] clearing a vector of pointers

查看:102
本文介绍了清除指针向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经定义了一个这样的类:

Assume I have defined a class like this:

 class foo {
 private: 
    std::vector< int* > v;
 public:
    ...
    void bar1()
    {
       for (int i = 0; i < 10; i++) {
         int *a = new int;
         v.push_back( a );
       }
    };

    void bar2()
    {
       std::vector< int >::iterator it = v.begin();
       for ( ; it != v.end(); it++ )  
         std::cout << (*it);
       v.clear();
    }
 };

简而言之,我向后推向量中的一些指针,然后清除向量.问题是,此代码是否存在内存泄漏?我的意思是通过清除向量,是否正确删除了指针?

In short, I push back some pointers in a vector, later I clear the vector. The question is, does this code has memory leak? I mean by clearing the vector, are the pointers deleted properly?

推荐答案

是的,除非删除指针,否则代码会发生内存泄漏.如果foo类拥有这些指针,则有责任删除它们.您应该在清除向量之前执行此操作,否则将丢失需要取消分配的内存的句柄.

Yes, the code has a memory leak unless you delete the pointers. If the foo class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.

   for (auto p : v)
   {
     delete p;
   } 
   v.clear();

使用适当的智能指针std::vector可以完全避免内存管理问题. >.

You could avoid the memory management issue altogether by using a std::vector of a suitable smart pointer.

这篇关于清除指针向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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