const question/suggestion

Myron Alexander someone at somewhere.com
Mon Jun 18 08:57:50 PDT 2007


Myron Alexander wrote:
> Craig Black wrote:
>> OK, I think I'm starting to grasp the subtle differences between 
>> const, final, and invariant.  It seems to me that to have three 
>> keywords is unnecessary.  Perhaps const and final could be merged into 
>> one?
>>
>> From my understanding, the only difference between const and final is 
>> that local final fields can be initialized in a constructor, right?  
>> Couldn't that just be the default behavior of a local const field?  
>> Then we could get rid of final and have only two keywords.  Or am I 
>> missing something?  IMO, two keywords is way less confusing than three.
>>
>> Another question.  Since invariant data should always be invariant, 
>> does it make sense to be able to cast non-invariant data to 
>> invariant?  The compiler will think that it is invariant when it isn't.
>>
>> -Craig
>>
> 
> Craig, const and final have two very different roles. Const ensures that 
> the value referenced/pointed to by the reference/pointer cannot be 
> changed. In other words, if an object reference is bound to a const 
> variable, then the object is immutable when referenced via that variable.
> 
> Final is different in that it prevents a variable from having another 
> value bound to it. In other words, if you have a reference variable, 
> once initialised, you cannot assign a new reference to the variable.
> 
> Examples:
> 
> SomeObject is a mutable class, IE it's value can be modified.
> 
> auto mutvar = new SomeObject ();
> mutvar.changesomething() -- ok
> 
> const var = new SomeObject ();
> var.changesomething() -- fails
> 
> Now for final:
> 
> final finvar = new SomeObject (); -- ok
> finvar.changesomething() -- ok
> ...
> finvar = new SomeObject (); -- fails
> 
> Regards,
> 
> Myron.

Oops, forgot to add this:

> const var = new SomeObject ();
> var.changesomething() -- fails

var = new SomeObject (); -- ok

Regards,

Myron.



More information about the Digitalmars-d-announce mailing list