1

I'm programming in c++ and wondering if I should manually deallocate a 2d vector. For example:

class A{
    private: vector<vector<int> > a;
    public: A(vector<int> &input0,vector<int> &input1){
    a.push_back(input0);
    a.push_back(input1);
   }
    ~A(){//should i do something here?}
}

int main(){
    vector<int> a0(3);
    vector<int> a1(3);
    A my_A(a0,a1);
}

In this example, should I deconstruct the private variable a in the deconstructor of class A? If yes, how should I do that?

mmirror
  • 175
  • 1
  • 3
  • 10

1 Answers1

4

No, you don't need to.

std::vector, as all standard library facilities, have destructors themselves, which take care of proper destruction. If you had to manually destruct it, users could easily forget destructing and would end up having an idle std::vector in memory.

However, if you ever should store heap-allocated objects in a std::vector: these you have to delete. The destructor of std::vector cannot know the pointers point to heap memory, so it won't free that memory. Just use a std::unique_ptr or std::shared_ptr in that case, whatever you need.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • Thanks! But what are heap-allocated objects? Does that mean that as long as I don't use something like "new" to allocate memory as well as pointers then I should be safe? – mmirror May 05 '16 at 16:25
  • @jyw Heap-allocated objects are objects allocated using `new`. In `int* i = new int;` `i` points to a heap-allocated object. Yes, it means exactly that. But as I said, you can also use `std::unique_ptr` or `std::shared_ptr` to `delete` heap-allocated objects automatically. – cadaniluk May 05 '16 at 16:48