I have a basic question on destructors.
Suppose I have the following class
class A
{
public:
int z;
int* ptr;
A(){z=5 ; ptr = new int[3]; } ;
~A() {delete[] ptr;};
}
Now destructors are supposed to destroy an instantiation of an object. The destructor above does exactly that, in freeing the dynamically alloctaed memory allocated by new.
But what about the variable z
? How should I manually destroy it / free the memory allocated by z
? Does it get destroyed automatically when the class goes out of scope?
It gets "destroyed" automatically, although since in your example int z
is a POD-type, there is no explicit destructor ... the memory is simply reclaimed. Otherwise, if there was a destructor for the object, it would be called to properly clean-up the resources of that non-static data member after the body of the destructor for the main class A
had completed, but not exited.
z
is automatically destroyed. This happens for every "automatic" variable. Even for pointers like int*
, float*
, some_class*
, etc. However, when raw pointers are destroyed, they are not automatically delete
d. That's how smart pointers behave.
Because of that property, one should always use smart pointers to express ownership semantics. They also don't need any special mentioning in the copy / move constructor / assignment operator, most of the time you don't even need to write them when using smart pointers, as they do all that's needed by themselves.
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