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();
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.)
source share