Calling members of null pointers-to-struct

Tor Myklebust tmyklebu at csclub.uwaterloo.ca
Sun May 6 14:55:27 PDT 2007


James Dennett <jdennett at acm.org> wrote:
> Tor Myklebust wrote:
> > Why is this illegal in D?  As I understand it (from discussion with 
> > GregorR on IRC), methods of a D struct are not virtual --- the following 
> > program cannot use vtables as an excuse for its AssertError.
> 
> [snip]
> 
> > (Except for one minor detail about foo not being initialised to null by 
> > default, this is perfectly good C++ code; calling a nonvirtual method of 
> > a null pointer-to-struct simply results in the 'this' parameter coming 
> > out to be null.  So, like, why doesn't D do the same?)
> 
> It's technically invalid in C++ also unless the function
> is a static member function.  The fact that most compilers
> allow it to run means nothing; in a portably valid C++
> program, the value of the "this" pointer is never null.
> 	
> If D requires this to be diagnosed in at least some modes,
> that would be a minor improvement on C++ (which leaves
> this as undefined, largely for performance reasons).

OK, what you say about the C++ standard is true; 9.3.2.1 says the this 
pointer is a pointer to the object on which the function is called, and 
there can't very well be such a thing if this is null.  (I still see no 
earthly reason why it *should* be invalid for nonvirtual functions --- 
by extension, I see no earthly reason why it should be invalid for 
methods in D structs.)

Tor Myklebust



More information about the Digitalmars-d mailing list