Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the destructor get called automatically

Tags:

c++

destructor

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?

like image 643
Dunes Avatar asked Feb 28 '12 18:02

Dunes


2 Answers

Yes, data will be destroyed automatically, you need not do anything to achieve it. vector will handle the cleaning up of the dynamic memory allocated by it. The vector's destructor will be called automatically when an instance of A is destroyed.

There is no difference in behavior irrespective of whether A is a class or struct.

like image 130
Naveen Avatar answered Oct 20 '22 02:10

Naveen


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 
}
like image 22
111111 Avatar answered Oct 20 '22 02:10

111111