What guarantees does D 'const' provide, compared to C++?

Era Scarecrow rtcvb32 at yahoo.com
Sun Aug 19 13:56:21 PDT 2012


On Sunday, 19 August 2012 at 20:14:50 UTC, Peter Alexander wrote:
> class Foo
> {
>     static Foo sneaky;
>     this() { sneaky = this; }
>     void bar() const { sneaky.x++; }
>     int x = 0;
> }
>
> const(Foo) f = new Foo();
> assert(f.x == 0);
> f.bar();
> assert(f.x == 1);
>
> You only have that guarantee if there are no other mutable 
> references to the data. const *on its own* does not provide 
> that guarantee.

  I don't think 'sneaky' counts. Static being there's only one of 
basically takes it outside the scope of the class/struct in it's 
own memory space. Re-written it's treated like this.

Foo sneaky;

class Foo
{
     this() { sneaky = this; }
     void bar() const { sneaky.x++; }
     int x = 0;
}

const(Foo) f = new Foo();
assert(f.x == 0);
f.bar();
assert(f.x == 1);

const(Foo) f2 = new Foo(); //a WTF moment?

assert(f.x == 1);
f.bar();
f.bar();
assert(f.x == 1);
assert(f2.x == 2);

  Besides likely the const/immutable and constructors can likely 
fix this, or maybe not. *shrugs* More likely the failures. In 
truth bar never modifies the allocated data (being Foo.x), sneaky 
although a reference is considered it's own thing.

  Besides weren't not talking about the data never changing, only 
the code calling can't change it (directly). If you don't want 
things to change, then A) don't write it to circumvent it, or B) 
Use immutable (then do Step A again)


More information about the Digitalmars-d mailing list