Why can delete operator be used in const context?

So I think delete p; may change the member p of rhs though rhs is a const reference.

  1. No. delete p; doesn't change p. Invalidation is not modification.

  2. Regardless, having a const reference to an object (rhs) does not by any means prevent the referred object form being modified. It merely prevents modification through the const reference. In this case we access the object through this which happens to be a pointer to non-const, so modification is allowed.

Someone may insist that "to render a pointer invalid is not to change the value of a pointer" but I don't find such a statement in the standard.

The behaviour of delete expression is specified in [expr.delete]. Nowhere in that section does it mention that the operand is modified.

Becoming invalid is specified like this:

[basic.compound]

... A pointer value becomes invalid when the storage it denotes reaches the end of its storage duration ...

Note that it is the value that becomes invalid. The pointer still has the same value because the pointer was not modified. The value that the pointer had and still has is simply a value that no longer points to an object - it is invalid.


Supplement: I've changed delete p; to delete rhs.p;, but it still works. Why?

Answer 2. From previous question no longer applies, but answer 1. does. delete rhs.p; does not modify rhs.p.


Calling delete on a member pointer frees the memory the pointer points to but does not change the pointer itself. Thus, it does not change the bitwise contents of the object, thus it can be done in a const member.

C++ only cares about bitwise const (of the object the method is invoked on). Not logical const. If no bits in the object change, then all is well - const wise - as far as the C++ language is concerned. It does not matter whether the logical behaviour of the object is changed (for example by changing something member pointers point to). That's not what the compiler checks for.