Aquivalent References as in C++?

Ali Çehreli acehreli at yahoo.com
Tue Apr 17 08:49:05 PDT 2012


On 04/17/2012 02:39 AM, Namespace wrote:

 >> Bar b = new Bar(42);
 >>
 >> new Foo(b); // works
 >> new Foo(null); // compiler error

That fails because null is a compile time value and you have a special 
template code for that that fails the compilation.

 >> new Foo(Bar(23)); // works
 >> new Foo(Bar(25)); // works
 >
 >
 > But if I write
 >
 > Bar bn;
 > new Foo(bn);
 >
 > it works also and doesn't throw a compiler error.

There, bn is a variable that has it's own life at runtime. Although the 
compiler can analyze the code to determine that bn never becomes 
anything but null, we may not want it to be too smart.

Imagine that there are lines after Bar bn; that you have just commented out:

Bar bn;
// bn = foo();
new Foo(bn);

Now the compilation would failure would be an annoyance. That's part of 
the reason why the compiler does not go that deep in its analysis.

 > To avoid this, I have to write an assert(obj !is null); again.

Yes, you must because whetheer obj is null is only known at runtime.

 > This really sucks. If anybody else works with my Code and puts a null
 > reference to any method he gets no compiler error and wonder why he gets
 > a runtime error instead.
 > Thats very annoying...

Ali



More information about the Digitalmars-d-learn mailing list