mutable keyword
ciechowoj via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 20 11:41:04 PDT 2016
On Thursday, 19 May 2016 at 23:21:14 UTC, Jonathan M Davis wrote:
> On Thursday, May 19, 2016 20:44:54 ciechowoj via
> Digitalmars-d-learn wrote:
>> Is there D equivalent of C++'s mutable keyword? Like the one
>> that allows to modify a field of struct from constant method.
>> Or some alternative solution?
>
> Now, if your functions aren't pure, you can put state outside
> of the object itself and have a const member function access
> and mutate that external state, but that's not exactly great
> for encapsulation, and then you can't use that function in pure
> code. But it's the closest thing to a backdoor from const that
> exists in D, because const is set up so that it's actually
> const and not just const until the implementation decides to
> mutate it anyway. Whether that's better or worse than C++'s
> const depends on what you're trying to do, but the reality of
> the matter is that D's const is ultimately very different from
> C++'s const because of how restrictive it is. You get better
> guarantees but can't use it anywhere near as much precisely
> because of the restrictions that are required to provide those
> guarantees.
>
> - Jonathan M Davis
Thanks for explanation. It makes implementing things like
shared_ptr somewhat troublesome when they are supposed to work in
const environment. Isn't there a way to escape a pure environment
(like trusted for safe)? Or/and would modifying an external state
from pure function be an undefined behavior?
More information about the Digitalmars-d-learn
mailing list