const member function

Foo via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 21 07:25:37 PST 2015


On Saturday, 21 February 2015 at 06:38:18 UTC, rumbu wrote:
> Often I'm using the following code pattern:
>
> class S
> {
>    private SomeType cache;
>
>    public SomeType SomeProp() @property
>    {
>       if (cache is null)
>         cache = SomeExpensiveOperation();
>       return cache;
>    }
> }
>
> Is there any way to mark SomeProp() as const? Because I want to 
> call somewhere const(S).SomeProp, which for the outside world 
> is must be "const", returning just a value, even that internaly 
> it modifies the internal S structure.

AFAIK it is unsafe and not recommended, but this works for me:

----
import std.stdio;

class Foo {
     void say(string s) const {
         writeln(s);
     }
}

class Bar {
     Foo f;

     const(Foo) getFoo() const {
         if (!f)
             cast() this.f = new Foo();
         return f;
     }
}

void main() {
     Bar b = new Bar();
     const Foo f = b.getFoo();
     f.say("Hello");
}
----


More information about the Digitalmars-d-learn mailing list