How to manually destroy member variables?

I have a basic question about 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 must destroy the instance of the object. The destructor above does just that, freeing dynamically alloctaed memory allocated by the new one.

But what about the variable z ? How can I manually destroy / free the memory allocated by z ? Will it be automatically destroyed when the class goes beyond?

+4
source share
5 answers

It is automatically "destroyed", although since int z is a POD type in your example, there is no explicit destructor ... the memory is simply restored. Otherwise, if there was a destructor for the object, it would be called to properly clean up the resources of this non-static data element after the body of the destructor for the main class A completed, but did not exit.

+5
source

z automatically destroyed. This happens for every โ€œautomaticโ€ variable. Even for pointers like int* , float* , some_class* , etc. However, when the original pointers are destroyed, they do not automatically delete d. This is the behavior of smart pointers.

Because of this property, smart pointers should always be used to express ownership semantics. They also do not require special mention in the constructor / assignment operator copy / move, most of the time you do not even need to write them when using smart pointers, since they do everything that you need.

+4
source

Destroying an object will also destroy all member variables of that object. You only need to delete the pointer, because destroying the pointer does nothing - in particular, it does not destroy the object that the pointer points to or frees its memory.

+2
source

In fact, it is automatically destroyed when the class goes beyond. A very good way to guess if the fact is that after its announcement there is no * .

0
source

For PODS (plain old data types), such as int, floats, etc., they are automatically destroyed. If you have objects as data elements (for example, std::string aStr; ), their destructors will be automatically called. You only need to manually control the freeing of memory (for example, above) or any other manual object or data cleaning (for example, close files, free resources, etc.).

0
source

Source: https://habr.com/ru/post/1390507/


All Articles