How can we call "delete this?" In const-member function?

I saw the code snippet as follows:

class UPNumber { public: UPNumber(); UPNumber(int initValue); ... // pseudo-destructor (a const member function, because // even const objects may be destroyed) void destroy() const { delete this; } // why this line is correct??? ... private: ~UPNumber(); }; 

Firstly, I am sure that the definition of the above class is correct. Here is my question, why can we define the destroy function as described above? Is the reason that we can change the 'this' in the const member function?

+4
source share
4 answers

The const qualifier applied to a method has the effect of passing this it a const pointer; in particular, in your case it will be const UPNumber * .

However, this is not a problem for delete : in fact, you can use delete for the const pointer without having to do anything as indicated in Β§5.5.5 ΒΆ2:

[Note: a pointer to a const type may be an operand of a delete expression; there is no need to discard the constant (5.2.11) of the pointer expression before it is used as the operand of the delete expression. ]

Note that before the standard was completed, there was a lot of discussion about whether it was or was not a good idea, so some preliminary standard compilers throw an error when trying delete const pointers.

The idea behind this behavior is that otherwise you would not have a path to delete const objects without using const_cast ; see this question for more information.

+4
source

This works for the same reason as this work:

 const int* upn = new int(); delete upn; 

You can delete pointer to an object constructed with const. Constant qualification in a member function simply means that this is of type const UPNumber* .

+10
source

Where did you get the idea that we are changing this ? In fact, this not an lvalue. It cannot be changed, whether the member function is const or not.

Applying a delete expression to a pointer (any pointer, not just this ) is by no means considered a modification of that pointer. Moreover, the delete-expression argument is treated as an rvalue, which means that it cannot be changed with delete .

So in your code there is no problem with this delete application.

+2
source

As technically possible and defined for calling delete this , provided that you are careful , the constant of the suicide method is technically meaningless , since the object cannot be touched after the call.

This is why it is semantically incorrect to have a const method that calls delete this .

An interesting point was the commentary by Steve Jessep . Launching the destructor does not leave the object unchanged, so the use of the concept of constness is doubtful.

0
source

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


All Articles