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();
};
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?
The
constqualifier applied to a method have the effect of making thethispassed to it aconstpointer; in particular, in your case it will be aconst UPNumber *.Still, this is not a problem for
delete: actually you can usedeleteon aconstpointer without having to cast anything, as specified at §5.3.5 ¶2: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
deleteconstpointers.The idea behind allowing this behavior is that otherwise you would have no way to
deleteconstobjects without using aconst_cast; see this question for more info.