assert(obj) is a mystery

Davidson Corry davidsoncorry at comcast.net
Thu Nov 10 11:26:09 PST 2011


On 11/9/2011 5:12 PM, Jonathan M Davis wrote:
>> As far as I can tell, "assert(obj)" MEANS "test the invariant without
>> using the object". And I don't see the point of that.
>
> It's occasionally useful when debugging code - particularly when called from
> inside of the object rather than externally.
>
>> Alex's original complaint, if I understand it correctly, is that a bare
>> mention of "obj" anywhere else is evaluated as a Boolean "obj !is null".
>> ONLY IN "assert(obj)" does it have the special meaning of "obj !is null
>> &&  obj.invariant_holds".
>
> No, his complaint is that it does obj.invariant_holds _without_ checking for
> null. What everyone initially expects is that assert(obj) is identical to
> assert(obj is null) - since that's how it works in all other cases (if, while,
> etc.). The fact that it runs the invariant isn't really a problem IMHO. Since,
> the invariant shouldn't be failing, it's just additional overhead, and since
> it's compiled out in release mode, that really isn't a problem. It's the fact
> that it doesn't first check for null which makes it so that it not only
> completely changes the semantics of implicitly converting a class reference to
> bool but that it will kill your program in cases where the object is null. So,
> as long as it's changed from just testing the invariant to testing for null
> and _then_ testing the invariant if it's not null, I think that it's fine.
>
> As rare as it may be to need to explicitly test the invariant, having a way to
> do so is definitely not detrimental to the language. It's just how it's
> currently implemented that's horribly broken.

Ah. Now I understand. Thanks to all.   -- Davidson


More information about the Digitalmars-d-learn mailing list