Casting Pointers?

Johannes Pfau via Digitalmars-d digitalmars-d at puremagic.com
Thu May 12 10:29:16 PDT 2016


Am Thu, 12 May 2016 09:38:27 +0000
schrieb Dicebot <public at dicebot.lv>:

> On Thursday, 12 May 2016 at 09:33:54 UTC, Dicebot wrote:
> > On Thursday, 12 May 2016 at 08:41:25 UTC, John Burton wrote:  
> >> Is this legal / valid in D and if not what is the appropriate 
> >> way to efficiently access data like this?  
> >
> > We rely on this cast to be legal and well-defined in a lot of 
> > Sociomantic code, banning would be a real disaster :X  
> 
> (most common case is casting between `char[]` and `struct S { 
> char[]; }`)

That cast is safe even with strict aliasing rules:
http://stackoverflow.com/questions/9747010/does-accessing-the-first-field-of-a-struct-via-a-c-cast-violate-strict-aliasing
So it's highly unlikely this will ever become undefined behavior in
D :-)

In the end a compiler writers can make up arbitrary aliasing rules: For
example in D ubyte[] should probably alias all [] slices, ubyte*
aliases all pointers (like char* in C), ...

double and long are fundamentally different though, so aliasing
wouldn't be allowed for these types in most languages. AFAIK no D
compiler actually enforces strict aliasing right now. GDC
explicitly disables all aliasing related optimizations.


More information about the Digitalmars-d mailing list