Any word on the return-type const syntax?

Sönke Ludwig ludwig at informatik_dot_uni-luebeck.de
Sun Dec 9 15:36:13 PST 2007


Janice Caron wrote:
> On 12/9/07, Robert Fraser <fraserofthenight at gmail.com> wrote:
>> Janice Caron wrote:
>>> No, sorry - I figured out the problem. Invariant classes and invariant
>>> member functions make no sense. This was discussed in another thread
>>> somewhere, and Walter agreed.
>> Link? More than half of the classes I write are invariant after
>> construction, and having the compiler be able to optimize that would be
>> great (Java 6's HotSpot can, after all, without any special marking in
>> the code).
> 
> Sorry, I can't remember, but just ask Walter for his current opinion
> (and if it's different from his previous opinion, so be it).
> 
> Basically, it boils down to the fact that
> 
>     invariant C = new C;
> 
> won't compile, because mutable won't implicitly convert to invariant.
> For that, you'd need Walter to add a language construct like
> 
>     invariant C = inew C;
> 
> ...which of course doesn't exist. I know you could always write
> 
>     invariant C = cast(invariant(C)) new C;
> 
> but casts are a last resort, as they're error-prone.
> 
> Assuming we decide we /do/ have to support invariant classes after
> all, then the compiler was correct to flag the error that it did. The
> line in question was
> 
>>>>         invariant(T)* ptr() invariant { return a.ptr; }
> 
> and that error arises because T* (the type of a.ptr) will not
> implicitly convert to invariant(T)*. If you really wanted to support
> invariant classes, that line would have to be changed to:
> 
>     invariant(T)* ptr() invariant { return cast(invariant(T)*) a.ptr; }
> 
> Simply put - invariant classes lead to lots of casting. And they're
> pointless anyway, because Walter said (...and I'm sorry, I can't find
> you a link, but I'm sure he'll read this and correct me if I'm
> wrong...) that invariant classes don't help with optimization anyway,
> so why bother with them?

I have actually changed a bunch of classes to be invariant, that is, they are 
declared as "invariant class C {}". At least, if they are used like this, no 
extra casts are necessary. "new C" works, and inside of the class nothing needs 
to be manually declared invariant using a cast.

The main benefit here is not compiler optimization, but by knowing some instance 
is invariant, you can use this instance from any number of threads without 
worrying about locking/synchronization. I think this can sometimes be a very 
useful feature to enforce instance invariantness in the language (and to 
document it at the same time).



More information about the Digitalmars-d mailing list