简体   繁体   English

C ++中的指针,重分配和向量

[英]pointers,deallocation and vector in c++

I want to know that should i explicitly deallocate the pointers which are erase from a vector by myvector.erase(); 我想知道我是否应该通过myvector.erase()显式取消分配从向量中删除的指针; .

For example; 例如;

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

There's no way we could possibly know, since we don't know what you're trying to do. 我们可能无法知道,因为我们不知道您要做什么。 But the basic answer is: 但是基本的答案是:

  1. If the collection logically owns the things in it, you are doing it all wrong. 如果集合在逻辑上拥有其中的东西,则说明您做错了所有事情。 Never use ordinary collections of ordinary pointers for this purpose. 切勿为此目的使用普通指针的普通集合。 Things will go horribly wrong if you, for example, copy the collection. 例如,如果您复制收藏集,事情将会变得非常糟糕。 (Either use ordinary collections of smart pointers or collections specifically designed to hold pointers and manage the lifetimes of the objects in them.) (可以使用普通的智能指针集合,也可以使用专门设计用于保存指针并管理其中对象寿命的集合。)

  2. If the collection does not own the things in it, then do not delete pointers from the collection. 如果集合不拥有其中的所有内容,则不要从集合中delete指针。 That will cause other code that uses those pointers to access an object after it has been deleted. 这将导致其他使用这些指针的代码在删除对象后访问该对象。

You shall delete the element by yourself. 您应该自己删除该元素。 vector did not allocate that element and so it will not free it. 向量没有分配该元素,因此不会释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM