Casting away immutability

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 2 22:15:24 PDT 2015


On Wednesday, September 02, 2015 14:00:07 Sergei Degtiarev via Digitalmars-d-learn wrote:
> On Wednesday, 2 September 2015 at 04:19:24 UTC, lobo wrote:
> > No, I think your design is unsafe because you're throwing away
> > type information and returning void[], then telling the
> > compiler not to worry about it.
> It is unsafe, but this not my design but std.mmfile module in
> phobos. This is what I'm trying to improve. And there was no type
> information initially, this is raw allocated memory returned to
> user.

Well, that's how mmap works. You're just getting raw bytes as void*, and
the D code converts that to void[], which is slightly safer. It doesn't
inherently have a type, and often, the data referred to by mmap never did
have a type. It's just bytes in a file. So, if you want to use it as a type,
you have to tell the compiler what it's type is - and get it right - via a
cast. And yes, you can cast to immutable as part of that, because casts let
you shoot yourself in the foot, because you're telling the compiler that you
know better than it does, but you shouldn't be casting anything you get from
C to immutable, because it's not going to be immutable. Most code shouldn't
be casting to immutable any more than it should be casting away immutable.

immutable data is treated by the compiler as immutable - it will _never_
change over the course of the program - so if it does change, you're going
to have fun bugs, and if it really refers to mutable data (as would be the
case with an mmapped file), then it could change. Additionally, immutable
is treated as implicitly shared, so the compiler could do different
optimizations based on that (though that probably won't affect anything if
you only ever have it one a single thread), and if it's not really
immutable, you could have fun bugs caused by that.

Don't cast to or from immutable unless you know what you're doing, and in
most of those cases, there's a decent chance that that's not the best way to
do what you're trying to do anyway.

But at the end of the day, the cast operator is a blunt instrument which
inloves you telling the compiler that you know better than it does, so you
had better know better, or you're going to shoot yourself in the foot.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list