const member function
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Feb 21 00:08:26 PST 2015
On 2/21/2015 4:31 PM, rumbu wrote:
> My intention is not to have a read-only getter, I want to call SomeProp
> on a const object:
>
> class S
> {
> private int cache = -1;
> private int SomeExpensiveOp() { return 12345; }
>
> public @property const(int) SomeProp()
> {
> if (cache = -1)
> cache = SomeExpensiveOp();
> return cache;
> }
> }
>
const is transitive. If an instance of S is const, then all of its
members are const, too. You cannot modify cache in that case. Assuming
cache only needs to be initialized once, you can do this instead:
this() { cache = SomeExpensiveOp(); }
public @property const(int) SomeProp() const
{
return cache;
}
Notice the const on the end of SomeProp. That makes the function
callable on a const instance, but you still cannot modify cache inside
of it.
More information about the Digitalmars-d-learn
mailing list