C++ 清除指针向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12795196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:37:50  来源:igfitidea点击:

clearing a vector of pointers

c++pointersmemory-leaksvector

提问by mahmood

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?

简而言之,我将向量中的一些指针推回,然后我清除了向量。问题是,这段代码有内存泄漏吗?我的意思是通过清除向量,是否正确删除了指针?

回答by juanchopanza

Yes, the code has a memory leak unless you delete the pointers. If the fooclass 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.

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

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

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

您可以通过使用std::vector一个合适的智能指针来完全避免内存管理问题。

回答by Tim Kuipers

I think the shortest and clearest solution would be:

我认为最短和最清晰的解决方案是:

std::vector<Object*> container = ... ;
for (Object* obj : container)
    delete obj;
container.clear();

回答by Tim Kuipers

Nope you only clear the vector storage. Allocated memory with 'new' is still there.

不,您只清除矢量存储。使用“new”分配的内存仍然存在。

for (int i =0; i< v.size();i++)
   {
     delete (v[i]);
   } 
   v.clear();

回答by tozka

You can use for_each:

您可以使用for_each

std::vector<int*> v;

template<typename T>
struct deleter : std::unary_function<const T*, void>
{
  void operator() (const T *ptr) const
  {
    delete ptr;
  }
};

// call deleter for each element , freeing them
std::for_each (v.begin (), v.end (), deleter<int> ());
v.clear ();