Active destructor call

In this post:

C ++ pointer: changing content without changing address?

User Eric Postpischil suggested an answer in which he actively called the class destructor. It is legal? Is this considered good programming?

I ask that in one of my classes my teacher said that it was forbidden, and we should never do this, was he wrong?

The question and the answer itself to this post, although interesting, is not relevant to my question.

+4
source share
2 answers

Well, just like the process of creating a dynamic object can be “parsed” into two stages: raw allocation of memory and actual initialization (for example, calling the constructor via placement-new), the process of destroying a dynamic object can also be “parsed” into two stages : actual de-initialization (call of the destructor) and freeing memory. (As you can see, these two processes are mirror images of each other.)

This is very useful in situations where you want to use your own memory allocation / deallocation mechanism. Of course, in many cases you can achieve the desired effect by overloading operator new/delete , but in some cases it is not flexible enough and you can explicitly perform the above steps.

So here is one example of when a direct call to the destructor is a useful function. There are many others. And yes, this is completely legal.

When your class teacher said you should never do this, it probably means that you should avoid this now as part of your current curriculum. As you progress in your research, you will realize that many “you should never do this” tricks are actually very useful methods that belong to the category of “do this if you know what you are doing.” Of course, you should not abuse this technique, as it is really low-level.

PS This syntax is formally called a pseudo destructor call because it allows you to "call" non-existent destructors

 typedef int INT; INT i; i.~INT(); // <- legal code, pseudo-destructor call, no op 

The above legitimate C ++ code, despite the fact that INT not a type of class and therefore does not have a destructor. (Just do not try to do i.~int() - this is illegal. Named name must be used for non-class types.)

+5
source

C ++ destructors, of course, are not illegal and not forbidden or bad (unless you are mistaken, of course). So yes, strictly speaking, your teacher was wrong (although he may have simply been trying to find another point).

The most common examples of this are classes that use dynamic memory allocation. Simply put, when a destructor is called in a class that has allocated memory for itself on the stack, this memory is not freed. This means that there is memory on the stack that is reserved, but no one refers to it, that is, you cannot get it. In other words, you have a memory leak. However, if you correctly create the destructor and manually free the memory, you will avoid a memory leak.

+2
source

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


All Articles