On Monday, February 23, 2015 09:12:33 rumbu via Digitalmars-d-learn wrote: > On Saturday, 21 February 2015 at 15:26:28 UTC, ketmar wrote: > > On Sat, 21 Feb 2015 08:27:13 +0000, rumbu wrote: > > > >> 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. > > > > is there a way to been safely hit by a truck? > > I thought if there is some language construct similar to @trusted > for @safe, applicable to const member functions. You can be > safely hit by a truck if I tell you that there is no truck around > :)
No. That wouldn't work at all because of immutable. A const method can be called on an immutable variable just as well as it can be called on a const or mutable one. In addition to that, Walter Bright feels very strongly that const should provide actual compiler guarantees, and when you have something like C++'s mutable which gives you a backdoor on const, the compiler can't really guarantee much of anything. @trusted has similar problems in that the programmer can screw it up and mark stuff as @trusted which makes the calling code unsafe, but that would be an actual bug in the program, whereas C++s mutable isn't a bug. Mutating const is perfectly acceptle in C++. It just doesn't work unless you tell the compiler to let you do it anyway, and the behavior is well-defined, whereas doing anything like casting away const and mutating a variable in D is undefined behavior, because the compiler is free to rely on const variables not changing so long as it can guarantee that a mutable reference to the same data can't have mutated that data. And yes, on some level, that sucks, because stuff like caching doesn't work with const, but it does mean that you can rely on const actually being const, which does provide other benefits. It does take some getting used to though. Regardless, the fact that we have immutable pretty much forces the issue - especially when you consider that the compiler can choose to put immutable variables in read-only-memory if it thinks that makes sense. - Jonathan M Davis