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

Hasan Aljudy hasan.aljudy at gmail.com
Fri Mar 9 20:19:18 PST 2007



Jarrett Billingsley wrote:
> "Chris Warwick" <sp at m.me.not> wrote in message 
> news:est5n5$1krh$1 at digitalmars.com...
>> Errm so what does "if (object)" and "Assert(object)" do??
> 
> "if(object)" is the same as "if(object !is null)".
> 
> But "assert(object)" is a little tricky.  It's a little-known feature.  If 
> you use "assert(object)", it will call any invariants defined for the 
> object, i.e.
> 
> class C
> {
>     invariant
>     {
>         writefln("foo");
>     }
> }
> 
> ...
> 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!


More information about the Digitalmars-d-learn mailing list