How can we call "delete this; " in a const-member function?
I saw the code snippet as follows:
class UPNumber {
public:
UPNumber();
UPNumber(int initValue);
...
// ps开发者_StackOverflow中文版eudo-destructor (a const member function, because
// even const objects may be destroyed)
void destroy() const { delete this; } // why this line is correct???
...
private:
~UPNumber();
};
First, I am sure that above class definition is correct. Here is my question, why we can define the function 'destroy' as above? The reason being asking is that why we can modify 'this' in a const-member function?
That works for the same reason that this work:
const int* upn = new int();
delete upn;
You can delete
a pointer to a const-qualified object. The const-qualification on the member function just means that this
has a type const UPNumber*
.
The const
qualifier applied to a method have the effect of making the this
passed to it a const
pointer; in particular, in your case it will be a const UPNumber *
.
Still, this is not a problem for delete
: actually you can use delete
on a const
pointer without having to cast anything, as specified at §5.3.5 ¶2:
[Note: a pointer to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the pointer expression before it is used as the operand of the delete-expression. ]
Notice that, before the standard was completed, there have been many discussion about whether this was or wasn't a good idea, so some pre-standard compilers will issue an error when trying to delete
const
pointers.
The idea behind allowing this behavior is that otherwise you would have no way to delete
const
objects without using a const_cast
; see this question for more info.
Where did you get the idea that we are modifying this
? In fact, this
is not an lvalue. It It cannot ever be modified, regardless of whether the member function is const
or not.
Applying delete-expression to a pointer (any pointer, not just this
) is not in any way considered a modification of that pointer. Moreover, the argument of delete-expression is treated as rvalue, meaning that it cannot possibly be modified by delete
.
So, there are no problems with that application of delete
in your code.
As it is technically possible and defined to call delete this
provided that you are careful, the constness of the "suicide" method is technically pointless, since the object must not be touched after the call.
That's why it is semantically incorrect to have a const
method calling delete this
.
An interesting point brought Steve Jessep's comment. Running the destructor doesn't keep an object unchanged, so applying the concept of constness is questionable.
精彩评论