'final' variables
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Tue Mar 20 17:19:29 PDT 2007
Derek Parnell wrote:
> On Tue, 20 Mar 2007 16:52:14 +0100, Frits van Bommel wrote:
>
>> Stewart Gordon wrote:
>>> Tyler Knott Wrote:
>>>> Lionello Lunesu Wrote:
>>>>> What's the use of "final" for variables? I'm saying "for
>>>>> variables" because for methods the benefit is only too clear.
>>>> Because the "const" keyword is being repurposed for read-only
>>>> references to mutable or non-mutable data, we need a new
>>>> keyword for non-mutable variables.
>>> <snip>
>>>
>>> C++ manages with const for both, so why can't D? What circumstance is there in which either keyword would be valid with different meanings?
>> If you apply "const" to a class reference, how would you determine which
>> of {reference,object} the const applies to?
>>
>> - If to the reference only, you can't express the constness of objects.
>> - If to the object only, you can't express non-rebindability of the
>> reference. (C++ doesn't have this problem, since the only references it
>> has are implicitly final all by themselves)
>> - If to both, you can only express constness of objects by
>> simultaneously disallowing the reference to be rebound. Not nice.
>>
>> I think that covers all cases (except 'neither', but that simply doesn't
>> make any sense ;) ).
>
> What happens with ...
>
> final const Foo f;
> invariant Foo f;
>
> do either of these mean that both the reference and the object is not to be
> modified?
>
In the first decleration, the referance cannot be changed, and provides only an immutable
view into the object, so the object cannot be modified /by/ the referance 'f'. It is a
final variable, of type const Foo.
In the second decleration, the referance is mutable, but the object is guaranteed
unchanging. It is a standard variable, of type invariant Foo.
If you wanted to absolute guarantee that 'f' itself never changes, and the underlying
object does likewise, it'd be: final invariant Foo f;
If I'm following all this right...
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list