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?
No. D's const and immutable provide no backdoors. Rather, they provide strong guarantees. So, if a variable is const, then it cannot be mutated (even internally) except via a mutable reference to the same data. This has the upside that you can rely on a const object not mutating on you unless you're also messing around with mutable referencs to the same data, but it has the downside that you can't do things like caching or lazy initialization, and you can't have portions of a const object be treated as mutable. You can cast away const, but it's undefined behavior if you mutate afterwards (and could result in subtle bugs depending on what optimizations the compiler does). So, it's not going to provide a backdoor around const's strong guarantees about mutation. The result is that if you need something like C++'s mutable, you can't use D's const. You're stuck using mutable values and are forced to avoid const. 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