'final' variables

Derek Parnell derek at nomail.afraid.org
Tue Mar 20 16:18:43 PDT 2007


On Tue, 20 Mar 2007 14:03:34 -0700, Andrei Alexandrescu (See Website For
Email) wrote:

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

Now I know (really) that new keywords are *to be avoided at all costs*, but
this looks nice to me ...

   literal char[] s = "hello";

meaning that neither 's' can be changed nor can the data 's' points to.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Justice for David Hicks!"
21/03/2007 10:17:22 AM



More information about the Digitalmars-d mailing list