In this paragraph of C++ FAQ usage of delete this
construct is discussed. 4 restrictions are listed.
Restrictions 1 to 3 look quite reasonable. But why is restriction 4 there that I "must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it"?
I mean this
is yet another pointer. Why can't I reinterpret_cast
it to an int
or call printf()
to output its value?
The value of 'this' after calling delete is undefined, and the behaviour of anything you do with it is also undefined. While I would expect most compilers to do something sensible, there's nothing (in the spec) stopping the compiler from deciding that its behaviour in this particular case will be emit code to format your hard-disk. Invoking undefined behaviour is (almost) always a mistake, even when your particular compiler behaves in the way you'd like it to.
You could work around this by taking a copy of the pointer (as an integer) before calling delete.