'final' variables
Lionello Lunesu
lionello at lunesu.remove.com
Tue Mar 20 23:08:15 PDT 2007
"Walter Bright" <newshound at digitalmars.com> wrote in message
news:etpb8a$bfe$1 at digitalmars.com...
> Lionello Lunesu wrote:
>> I understand, but what's the point of telling the compiler "I don't want
>> to rebind this variable"? It doesn't seem like an optimization hint. Like
>> telling "func(const int i)" in C++ doesn't actually do anything. You just
>> type more.
>
> Final is handy for a number of things:
> 1) For class members, it would indicate that a class is not mutable once
> it's constructed. Probably most classes are like this, and so it's a handy
> way to document it.
Yeah, I see now how that would be handy. It's C#'s "readonly".
> 2) Andrei pointed out to me that one can often replace:
> auto x = initializer;
> with:
> final x = initializer;
> to indicate in a block of code that x will never be reassigned. This aids
> in understanding the code. It's a style I intend to adopt.
OK, "final x" means that you can skip big pieces of code, knowing that "x"
will not change.
> 3) For cases like:
> const char[] s = "hello";
> is it s that's not rebindable, or is the data that s is pointing to
> immutable? This never fails to confuse me (in C++), so I like to be able
> to say which it is in a clear manner.
Will "const" imply "final"? Hm, guess not, since you'll still want to write
"const char* x" and reassign 'x' later. But now I'm thinking too much C++.
>> And if you later want to rebind 'i' you'll have to change the interface.
>> Lose-lose?
>
> Although final is specified in the interface, it is not part of the
> interface. It only affects the implementation of the interface. You'll be
> able to change it without affecting any users of the interface.
Ah, that alone makes it a lot more practical than (half of) C++'s const.
Good one.
Some good points. Thanks.
L.
More information about the Digitalmars-d
mailing list