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?
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
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With