Is it safe in D to cast pointers to structures like this?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Tue Jan 14 12:56:22 UTC 2020


On Tuesday, 14 January 2020 at 12:05:01 UTC, John Burton wrote:
> After years of C++ I have become paranoid about any casting of 
> pointers being undefined behavior due to aliasing so want to 
> see if :-

FWIW, this is safe and portable in C++20:

https://en.cppreference.com/w/cpp/numeric/bit_cast


> 1) This is safe to do in D.
> 2) If not is there anything I can do to make it safe.
> 3) If not, what is the best approach?

What is legal in C, should in theory be legal in D unless the 
documentation states otherwise as the goal for D is to make 
porting C code to D easy. Hence, type punning through union 
should be ok.

I am not sure what the various D compilers do with aliasing, but 
allowing type punning through pointers can inhibit some 
optimizations.



More information about the Digitalmars-d-learn mailing list