由于 C++ 别名规则,您不能随意将 (一个 int*) 指向 char
数组,这似乎达成了一些共识。
从另一个问题——Generic char[] based storage and avoiding strict-aliasing related UB -- 似乎允许通过placement new(重新)使用存储。
alignas(int) char buf[sizeof(int)];
void f() {
// turn the memory into an int: (??) from the POV of the abstract machine!
::new (buf) int; // is this strictly required? (aside: it's obviously a no-op)
// access storage:
*((int*)buf) = 42; // for this discussion, just assume the cast itself yields the correct pointer value
}
那么,上面的 C++ 是否合法和是真正需要的放置 new 以使其合法吗?
最佳答案
是的,放置 new
是必需的,否则您将违反严格的别名(赋值为 access )。
以上合法吗?几乎(尽管它几乎适用于所有实现)。您通过强制转换创建的指针不指向对象,因为(现在已销毁)数组和 int
对象不是 pointer-interconvertible ;使用 std::launder((int*)buf)
,或者更好的是,使用放置 new
的返回值。
关于c++ - 将 int 放入 char 数组中是否需要放置 new 合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41624685/