简体   繁体   中英

Strict aliasing, pointer casting and std::launder

I learned unfortunately too late about strict-aliasing rule and C/C++ legit dereference after cast. As far as I understand the following code does break the aforementioned rule:

std::byte buffer[sizeof(double)];
double* x = reinterpret_cast<double*>(buffer);

*x = 45.35;

Is it allowed to use std::launder in the following way,

std::byte buffer[sizeof(double)];
double* x = std::launder(reinterpret_cast<double*>(buffer));

*x = 45.35;

so that the code is correct? How does it affect performances?

Then, it is possible to do something equivalent in some extension of C (without using unions or memcpy )? Does the -fno-strict-aliasing option make such kind of cast safer?

launder is unhelpful for this. Pre-C++20, both examples are UB. And while C++20 does make this valid (assuming the alignment for buffer is appropriate for double ), launder isn't what makes it work. Both of them are equally valid in C++20.

char buffer[sizeof(double)];
double* x = reinterpret_cast<double*>(buffer);

*x = 45.35;

This code is fine and doesn't violated the strict aliasing rule. It does exactly the same and you are free to copy your bytes to/from char afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM