Safety of casting away constness instead of using postblit

Jonathan M Davis jmdavisProg at gmx.com
Fri Oct 15 00:35:04 PDT 2010


On Friday 15 October 2010 00:09:22 Jonathan M Davis wrote:
> Okay. Bug http://d.puremagic.com/issues/show_bug.cgi?id=4867 is turning out
> to be a _big_ problem for the code that I'm working on at the moment. That
> combined with various bugs with regards to invariants is making dealing
> with const for certain things extremely difficult.
> 
> In this case, I have a struct which is a value type. It holds a long and a
> Rebindable which holds an immutable object. It _should_ be copyable without
> a postblit constructor, but the compiler apparently isn't smart enough to
> figure that out and complains up the wazoo. And thanks to the
> aforementioned bug, I can't _have_ a postblit. Bleh.
> 
> I can almost solve the problem on some level by creating a variable and
> then assigning to it with an overloaded opAssign(), except that the init
> for the struct type violates its invariant, so opAssign() blows up (maybe
> opAssign() shouldn't care about invariants...).
> 
> The only thing that I can think of (beyond giving up on const for some
> portions of my code until bug #4867 is fixed) is to just do the assignment
> but with a cast that casts away the constness of the struct. The question
> is whether this is safe. Since it's a struct, it should do a bit for bit
> copy, which should be totally valid, so I _think_ that it's safe, but I'd
> like to be sure. Does anyone know for sure if casting away constness like
> that would be safe?
> 
> - Jonathan M Davis

Well, it turns out that because I already had declared opCasts for the struct 
type in question, I had to declare one for itself to attempt a cast anyway. So, 
it's definitely safe in this case (albeit a hack, since I should just be able to 
use postblit). Still, it would be nice to know for sure if it's actually okay to 
cast away constness when a bit for bit copy should be okay.

- Jonathan M Davis


More information about the Digitalmars-d mailing list