c++ - C++ 中的指针、释放和 vector

标签 c++ pointers memory-management

我想知道我是否应该显式地解除分配由 myvector.erase() 从 vector 中删除的指针; .

例如;

Class Sample1{
   public:
         removeSample2(Sample2 * a)
         {
             if(// if i find that a is in my sampleList1 vector with index i ){
                   // should i call here delete or something like that for a pointer ?
                   sampleList1.erase(sampleList1.begin()+i);
              }
         }

   private:
      vector<Int *> sampleList1;

            } 

Class Sample2{
     public:
           // not important areas
     private:
          Sample1 * example;
             } 

最佳答案

我们不可能知道,因为我们不知道您要做什么。但基本的答案是:

  1. 如果集合在逻辑上拥有其中的东西,那你就大错特错了。切勿为此目的使用普通指针的普通集合。例如,如果您复制集合,事情就会变得非常糟糕。 (要么使用智能指针的普通集合,要么使用专门设计用于保存指针并管理其中对象生命周期的集合。)

  2. 如果集合不拥有其中的东西,则不要从集合中删除 指针。这将导致其他代码在对象被删除后使用这些指针访问对象。

关于c++ - C++ 中的指针、释放和 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16377876/

相关文章:

c++ - C++ 和 Scala 之间有多少互操作性?

c++ - 从一组坐标中确定将形成一条线的点

c++ - 静态类方法指针数组的正确语法

c - 如何通过指针访问全局定义的 typedef 结构?

C++ char 数组的动态数组

c++ - C++中的指针列表

memory-management - 什么是颠簸?为什么会发生?

c++ - 带有模板参数或类型名的模板函数

iphone - 实例变量未在内存中分配

iphone - iOS - 为什么我的 NSURL 没有保留在 init 方法中?