MaPo
MaPo

Reputation: 771

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?

Upvotes: 1

Views: 439

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473407

If you had allocated the byte array via malloc, operator new, or similar functions, launder would not be necessary, as the result of those operations is a pointer to the created object. However, when dealing with a byte array variable directly, launder is needed to reach the actual object created within that array.

However, that doesn't cause the object to exist. And pre-C++20's implicit object creation, no object actually exists there. So your code only works under C++20's rules (which are retroactively applied to previous standards via defect reports, though only more recent compilers would be able to apply them to compilation under older standards).

Upvotes: 2

Related Questions