const question/suggestion

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Jun 19 14:14:30 PDT 2007


Kristian Kilpi wrote:
> 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.

It has already been mentioned that you can 'cast(const) new Foo' to make 
it be treated as such (since you've cast it immediately upon creation, 
so there's no mutable referance available).  Likewise with 
'cast(invariant)'.  I'm thinking these might be relatively common 
operations for some, so maybe it would be wise/better/convenient to 
allow these keywords between 'new' and 'Foo' like 'new const Foo'.  If 
nothing else, it reads well to me, and provides type deduction.

auto  mvar = new           Foo ; //                 Foo  mvar ;
auto  cvar = new const     Foo ; //       const    (Foo) cvar ;
auto  ivar = new invariant Foo ; //       invariant(Foo) ivar ;
final fvar = new const     Foo ; // final const    (Foo) fvar ;

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-announce mailing list