From slices to perfect imitators: opByValue

Sönke Ludwig via Digitalmars-d digitalmars-d at puremagic.com
Thu May 8 09:47:18 PDT 2014


Am 08.05.2014 18:02, schrieb monarch_dodra:
> On Thursday, 8 May 2014 at 15:39:24 UTC, Sönke Ludwig wrote:
>> Unless I'm completely mistaken, it's safe to cast away const when it
>> is known that the original reference was constructed as mutable.
>
> Depends. If the original type referencing the (originally mutable)
> allocated data happens to be *im*-mutable, then it *would* be illegal to
> modify it, even if you *can*.
>
> EG:
>
> immutable myFirstRC = RefCounted!int(1);
> immutable myReference = myFirstRC;

This currently wouldn't compile, because all the RefCounted 
construction/destruction/postblit operations are not pure. But I agree 
that immutable is a different thing and would potentially break the cast 
- I was just talking about const references, because this is what 
frequently happens, even when *not* working with immutable data.

>
> In this particular case, you'd be modifying a ref count that can only be
> accessed via an immutable pointer. As such, the compiler is free to
> assume the value has never been changed, and avoid reading it all
> together, destroying your payload at the end of "myFirstRC"'s life-cycle.
>
> I honestly don't think (given D's transitive constness mechanics), that
> a const RefCount *could* make any sense.
>
> --------
>
> If you have const data referencing mutable data, then yes, you can cast
> away all the const you want, but at that point, it kind of makes the
> whole "const" thing moot.

There is of course always the alternative of using a global array of 
reference counts to implement this in a clean way, but ideally, there 
would be a way to semantically separate reference management data from 
payload data, so that immutable(RefCount!T) can be defined without 
working around the type system. But let's not clutter up this particular 
thread with RefCount related issues, it's a separate issue (AFAICS), and 
I really just brought it up as one example.


More information about the Digitalmars-d mailing list