Re: Reference to show that if (this == NULL) implies undefined
behaviour
On 2011-11-08 23:50:30 +0000, Johannes Sixt said:
On 8 Nov., 09:06, Carlos Moreno <moreno_n...@mailinator.com> wrote:
Wait a second --- notice that I said I'm trying to convince
someone that the trick invokes undefined behaviour; but the
thing is, his argument is that he got the idea from C++ books
(not sure which one(s), as I don't recall seeing the technique
in books), found it to produce simpler code than the alternative,
and it simply *works* on every existing compiler (well, I should
probably add that it is likely that it works on every existing
compiler).
It does not work with gcc. The following prints "this is not NULL",
even though the member function was clearly invoked on a null pointer:
And it probably gets the same result with any other compiler. But
different isn't the same. Changing to multiple inheritance or, as
mentioned earlier, changing to a virtual function, changes the context.
Calling a non-static member function requires an object. Somehow
magically calling a non-static member function without an object makes
the behavior of the program undefined. In the original example (no
inheritance, no virtual functions involved) there's no good reason for
a compiler to generate code that does unexpected things. Nevertheless,
the behavior of such a program is formally undefined, and writing code
like that is risky except with a compiler that explicitly documents
what it does.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]