Deallocating objects stored in a vector?

前端 未结 7 479
一生所求
一生所求 2020-12-10 06:17

I have a class that creates a vector of objects. In the deconstructor for this class I\'m trying to deallocate the memory assigned to the objects. I\'m trying to do this by

7条回答
  •  借酒劲吻你
    2020-12-10 06:51

    It's hard to say from your question just what the signature of maps is. I'm guessing you want to use delete[] because you also used new[]. So does that mean the members of your vector is itself a collection? supposing it is, then you have something like this:

    class Building {
      public:
        typedef int* maps_t;
      private:
        std::vector maps;
      public:
        Building();
        ~Building();
    };
    
    Building::Building(size_t num_maps) {
      for(;num_maps; --num_maps)
      {
        maps.push_back(new Building::maps_t[10]);  
      }
    }
    

    in that case, your destructor is nearly right; you need change only &maps[i] to maps[i].

    Building::~Building() {
        int i;
        for (i=0; i

    But in C++, we rarely like to do things that way. For one thing, unless you are actually trying to implement something like std::vector, you rarely want to use new[] or delete[] explicitly. You can, for example, use std::vector. You need perform no explicit memory management in that case. Your class will look like so:

    class Building {
      public:
        typedef std::vector maps_t;
      private:
        std::vector maps;
      public:
        Building();
    };
    
    Building::Building(size_t num_maps) {
      for(;num_maps; --num_maps)
      {
        maps.push_back(Building::maps_t(10));  
      }
    }
    

    There is no user defined destructor in this case, because std::vector already manages its own memory quite well.

提交回复
热议问题