How to deallocate object pointer in vector?

后端 未结 7 1382
野趣味
野趣味 2021-02-06 12:30

I have ;

class object {
                    // any private datas token in heap area 
             public : 
                   ~object () ; 

};
<
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 13:28

    You seem to be a bit confused. There are two concepts at play here:

    • How do I, the owner of tmp, deallocate the objects referred to by the pointers within tmp?
    • What should the destructor for the object class (~object) do?

    These are not really that related. When you are finished with the tmp vector, you must manually go through and call delete on each of its elements in order to deallocate the memory occupied by the object object that the element points to. This is assuming the elements were allocated with new, of course.

    The purpose of the object destructor ~object is to deallocate everything that the object object owns, not to deallocate the object object itself. If the object object does not own any dynamically allocated data, it does not need to do anything.

    In other words, when you write delete tmp[i], two things happen:

    1. *(tmp[i])::~object() is called
    2. The memory pointed to by tmp[i] is deallocated

    Note that (2) happens even if (1) does absolutely nothing. The point of step (1) is to allow the object that is about to be deallocated to deallocate any of its member objects that need to be deallocated. The destructor's job is emphatically not to deallocate the object that it was invoked on.

    By way of explicit example:

    class object {
      private:
        int foo;
      public:
        object() : foo(42) {}
        ~object() { /* nothing to do here; foo is not dynamically allocated */ }
    };
    
    int main() {
      vector tmp;
      tmp.push_back(new object());
    
      // Do some stuff with tmp
    
      for (int i = 0; i < tmp.size(); ++i) {
        delete tmp[i]; // Calls ~object and deallocates *tmp[i]
      }
      tmp.clear();
    
      return 0;
    }
    

    Or, by contrast

    class object {
      private:
        int* foo;
      public:
        object() : foo(new int()) { *foo = 42; }
        ~object() { 
          // Now since foo is dynamically allocated, the destructor
          // needs to deallocate it
          delete foo;
        }
    };
    
    int main() {
      vector tmp;
      tmp.push_back(new object());
    
      // Do some stuff with tmp
    
      for (int i = 0; i < tmp.size(); ++i) {
        delete tmp[i]; // Calls ~object (which deallocates tmp[i]->foo) 
                       // and deallocates *tmp[i]
      }
      tmp.clear();
    
      return 0;
    }
    

提交回复
热议问题