Errm so what does "if (object)" and "Assert(object)" do??

torhu fake at address.dude
Sat Mar 10 02:05:34 PST 2007


Hasan Aljudy wrote:
> 
> Jarrett Billingsley wrote:
>> scope c = new C();
>> assert(c); // prints foo since it calls the invariant
>> 
>> This means that if you use "assert(objectReference)" on a null reference, 
>> you will (like with '==' !) get an access violation, since it tries to look 
>> up the invariant from a null reference.
>> 
>> Therefore, when doing an assert on an object reference, you should always 
>> use "assert(c is null)" or "assert(c !is null)". 
>> 
>> 
> 
> Really?
> I thought assert(object) just throws an assert error if the reference is 
> null!

It's mentioned here:
http://www.digitalmars.com/d/class.html#invariants

The funny part is that assert(obj !is null && obj) does *not* call the 
invariant.  So assert(obj) is a special case.

I think assert(obj) being the same as assert(obj !is null), and then 
being able to do 'obj.invariant' if you really want to explicitly check 
the invariant would a lot clearer.  Or even 'invariant(obj)'.

Calling the invariant explicitly might be useful in the middle of 
methods.  Then I think this.invariant or invariant(this), is a lot more 
readable than assert(this).

You want both a null check and an invariant check, you could then do 
'assert(obj && invariant(obj))' or assert(obj && obj.invariant)'.  Seems 
pretty obvious to me what that would do.

Maybe obj.invariant is the best way, since it doesn't try to hide that 
invariant really is a method?


More information about the Digitalmars-d-learn mailing list