【问题标题】:Do I need to deallocate object pointers in a vector?我需要释放向量中的对象指针吗?
【发布时间】:2026-02-13 13:15:01
【问题描述】:

我对解除分配向量内存的工作方式感到困惑。 对于下面的示例,

vector<Object*> vec;

for(int i = 0; i < 10; i++){
  Object* obj = new Object();
  vec.push_pack(obj);
}

//DEALLOCATE CODE HERE//

我应该怎么做才能正确释放 vec? 该程序似乎运行良好,但我不确定。

【问题讨论】:

  • 所有你new 你必须delete - vector 不会改变它的任何东西
  • 首选的方式是根本不动态分配,vector&lt;Object&gt; 在很多情况下是正确的选择
  • 只是不要使用 new,使用 std::unique_ptr 代替:
  • 只需迭代向量以删除每个元素,然后清除(如resize(0))它,看我的回答

标签: c++ memory vector


【解决方案1】:

避免使用新/删除:

std::vector<std::unique_ptr<Object>> vec;

for(int i = 0; i < 10; i++)
{
  vec.push_pack(std::make_unique<Object>());
}

unique_ptr 将负责删除

【讨论】:

    【解决方案2】:

    如何解除分配

    例如做

    for(auto o : vect){
      delete o;
    }
    vect.clear();
    

    注意你写了push_pack而不是push_back来填充向量


    制作完整的程序:

    #include <vector>
    using namespace std;
    
    class Object{};
    
    int main()
    {
      vector<Object*> vec;
    
      for(int i = 0; i < 10; i++){
        Object* obj = new Object();
        vec.push_back(obj);
      }
      for(auto o : vec){
        delete o;
      }
      vec.clear();
    }
    

    valgrind下编译执行:

    pi@raspberrypi:/tmp $ g++ v.cc
    pi@raspberrypi:/tmp $ valgrind ./a.out
    ==9157== Memcheck, a memory error detector
    ==9157== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
    ==9157== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
    ==9157== Command: ./a.out
    ==9157== 
    ==9157== 
    ==9157== HEAP SUMMARY:
    ==9157==     in use at exit: 0 bytes in 0 blocks
    ==9157==   total heap usage: 16 allocs, 16 frees, 20,358 bytes allocated
    ==9157== 
    ==9157== All heap blocks were freed -- no leaks are possible
    ==9157== 
    ==9157== For counts of detected and suppressed errors, rerun with: -v
    ==9157== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
    

    所有分配的内存都被释放

    【讨论】: