const member function
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Feb 21 01:26:41 PST 2015
On Saturday, February 21, 2015 08:27:13 rumbu via Digitalmars-d-learn wrote:
> On Saturday, 21 February 2015 at 08:08:25 UTC, Mike Parker wrote:
> > On 2/21/2015 4:31 PM, rumbu wrote:
> >
> > 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.
>
> My question was not how I do this, I know already. My question
> was if there is another way to safely call a non-const instance
> function on a const object.
>
> Initializing "cache" in the constructor will defeat the cache
> mechanism itself an that's I want to avoid.
Nope. If you want to use caching, you can't do it with const. D's const is
transitive, and it's not logical const. It's physical const. If _any_
portion of an object were to be mutated by a const function, it would
violate the type system. Unlike C++'s const, D's const provides actual
guarantees about the data not changing, which can be useful for some
optimizations but is outright required because of immutable. For instance,
imagine if your object were immutable and your const function were somehow
able to mutate on of the object's members (e.g. by casting away const). An
immutable object could be in read-only-memory, in which case, that would
segfault. And even if it didn't, it could cause really weird bugs due to the
fact that the compiler is free to assume that an immutable object never
changes and that an object can never be mutated via a const reference. The
fact that immutable objects are implicitly shared would make it even worse,
because then you'd risk thread-related issues to boot.
The reality of the matter is that if you want to do any kind of caching like
this, you either have to do the caching only in mutable functions (in which
case, the const function could take advantage of the cached value if it were
there but would have to calculate it if it hadn't been cached already), or
you can't do caching at all.
Ultimately, for better or worse, D's const is a very different beast from
C++'s const, and you can't approach them the same way.
This SO question discusses the issue:
http://stackoverflow.com/questions/4219600/logical-const-in-d
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list