'final' variables

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Tue Mar 20 14:03:34 PDT 2007


Walter Bright wrote:
> 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.
> 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.

And the compiler will have an excellent opportunity to optimize the code 
(e.g. it can enregister "x" without fear). It's a win-win deal. Believe 
me. I'm not wearing a tie.

> 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.

What still needs to be decided here is whether we want to automatically 
make s final too when seen in a data definition. This is a hack for 
existing code's sake, and also because many people actually mean to make 
final const strings more often than just nonfinal const strings. 
Probably final can be inferred via simple flow analysis at low or no 
extra cost, which would please everyone.


Andrei



More information about the Digitalmars-d mailing list