const question/suggestion

Kristian Kilpi kjkilpi at gmail.com
Tue Jun 19 02:38:44 PDT 2007


On Tue, 19 Jun 2007 00:55:21 +0300, Walter Bright  
<newshound1 at digitalmars.com> wrote:

> Myron Alexander wrote:
>> const var = new SomeObject ();
>
> The above line will fail because const declarations can only be  
> initialized with something that can be evaluated at compile time. The  
> example should be:
>
> 	const(SomeObject) var = new SomeObject();
>
>> var.changesomething() -- fails

Now I'm a bit confused... Oh, now I get it. (I hope.)
There can be constant views and constant, or literal, data. And literals  
are, of course, compile time, er, constants.

Sometimes 'const' means immutable and sometimes it means literal, compile  
time value...


At first I read:

   const foo = new Bar;  //or const Bar foo = new Bar;

as:

   final const(Bar) foo = new Bar;

That is, a final, constant view to an object (or, immutable reference  
(final variable) + immutable object (constant view).) Not as a constant  
view to a constant/literal object.

With value types, final will be sufficient:

   final int v = foo();

But with reference types, one must write "final const(...)"...? Uh, that's  
verbose. :/


With functions, you can write:

   void f(const Bar foo);

   f(new Bar);  //no need for compile time constant/literal

Ok, inside the function, 'foo' will be treated as a constant/literal, so  
it makes sense, kind of.
(And const-by-default function paramters are too inconsistent?... ;) )



Maybe I should also wonder this: how one can create an object that will be  
treated as invariant/constant?

   invariant Bar foo = new Bar;  //global variable; currently inline  
initialization not allowed though

   void f() {
     invariant obj = foo;
   }

Surely the object pointed by 'foo' will be invariant during the execution  
of the program.



More information about the Digitalmars-d-announce mailing list