一般来说,我对严格别名和std::launder有点困惑。按照标准,以下代码是 UB:
void foo(int x)
{
float *p = reinterpret_cast<float *>(&x);
*p = 1.0f;
std::cout << x << std::endl;
}
但是如果使用std::launder会出现 UB 吗?
void foo(int x)
{
float *p = reinterpret_cast<float *>(&x);
*p = 1.0f;
std::cout << *std::launder(&x) << std::endl;
}
事实上,在现代版本的编译器上(至少对我来说),两个版本的代码都可以正常工作,但第一个版本保证是 UB,而我很难理解第二个版本。
在许多论坛上(以及在一些文章中),第二个代码作为std::launderworking的示例给出,但出于正式原因,这不是仍然是 UB 吗?