Alex Rivera | Logout

Does the destructor get called automatically

Asked 2012-02-28T18:26:57.773
15

My question is simple, but I haven't been able to find the question anywhere.

If I have a class like such

class A {
    vector<int> data;
}

When an instance of A gets destroyed will data also get destroyed properly, or should I write a destructor for A that calls data's destructor? Basically I worried about whether the dynamic memory of vector will not be freed when an instance of A is destroyed. I suspect the answer is that data is freed properly, but I don't want to find out I'm wrong the hard way.

Further, if A was a struct would the destructor for data get called when a local instance of A falls out of scope?

Edit
Report

1 Answer

4

No need, data member's destructors are always called.

An explicit destructor is useful manual memory management

struct a{
    int* ip;
    a() 
    : ip(new int(5)) 
    { }

    ~a() { delete ip; }
};

That said, you should generally speaking use RAII containers (such as smart pointers) so I personally rarely write dtors there days.

And exception to that is to declare a base classes dtor as virtual.

struct base {
     virtual ~base() {}
};
struct child : public base {
    //base and child destructor automatically called 
}
answered 2012-02-28T18:28:54.193

Your Answer