是否将正确对齐和大小的数组转换和访问到未构造的平凡类型未定义行为?

Is casting and accessing an array of correct alignment and size to a not constructed Trivial Type undefined behaviour?

下面的代码定义的好吗?

struct S { int x; };
alignas(alignof(S)) char c_arr[sizeof(S)];
S *s_ptr = (S*)c_arr;
s_ptr->x = 5; // UB or not UB?

注意:S 有意定义为 Trivial Type

如果我们通过添加一个只将 X 设置为某个任意值而不通过放置 new 调用它的构造函数来使类型 none 变得微不足道,情况会改变吗?

这个问题不同于 this 问题,因为它不使用 malloc,并且还询问 none 琐碎的类型。

Is the following code well defined?

没有。它违反了所谓的 strict aliasing rule.

你一定要洗好指针:

S *s_ptr = std::launder(reinterpret_cast<S*>(c_arr));
s_ptr->x = 5; // not UB

在接受提案 P0593R6 之前,洗钱是不够的。相反,过去需要使用 placement-new 显式创建对象。当重新解释的类型不是“隐式生命周期类型”时,这仍然是必要的。