Re: Calling a non-virtual member function for a NULL instance
Matt Curtis wrote:
James Kanze:
What the implementation has to do behind the scenes
really shouldn't concern the programmer.
I agree absolutely, however I am interested in why the
standard says it's undefined - when writing the standard,
someone must have had at least a hunch that an alternative
implementation of non-virtual function calls would be
worthwhile (or that the common implementation would not be
possible on some platforms).
It has nothing to do with the possible implementation of
non-virtual function calls. By definition, p->f() is the same
as (*p).f(), *p dereferences p and dereferencing a null pointer
is undefined behavior. For this not to be undefined behavior
would take a special rule, and presumably, no one thought it
was worthwhile, or even a good thing.
FWIW, I've used a compiler which would crash with the above
code.
Do you remember which platform this was? Do you know how it
implemented non-virtual member function calls?
The compiler was Green Hills, in debugging mode. It verified
explicitly that the pointer was non-null before making the call,
as a debugging aid.
The reason I am asking about which platforms would break is
because I am interested in whether it would be possible for
the standard to define this behaviour.
Possibly... the compiler where it failed made it do so
intentionally, as a debugging aid, because it was undefined
behavior. But why? You can't do anything in the function
without running into problems.
As a programmer I agree that undefined behaviour should be
avoided, however I also believe that this mechanism would be
quite useful if the standard allowed it. But before I go
bothering those busy people I'd better check out the
implications of the change.
The problem is how to define it. Obviously, any attempt to
access any member variable or to call a virtual function in the
function would still have to be undefined behavior. So you'd
have to make a special exception where whether an expression was
legal or not depended on the contents of the function body.
I don't think it would go over. The standard committee already
made a concrete and intentional decision that even if the called
function is static, the calling expression must still be
evaluated, so p->f() is undefined behavior if p is a null
pointer, even if f is a static member. Having decided that the
behavior must be the same even for a static member, I can hardly
imagine them deciding that it will be different for some
specific content of the function.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]