c++ - 将 int 放入 char 数组中是否需要放置 new 合法?

标签 c++ language-lawyer primitive-types strict-aliasing placement-new

由于 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/

相关文章:

c++ - 如何在 Qt 中更改图表轴的标题?

c++ - 如何在 C++ 和 Unix 中获得堆栈溢出?

c++ - 从 map 中获取详细信息并将其保存到另一个 map 中?

c++ - 是否假定C/C++中的所有函数都返回?

c++ - 在溢出的情况下,i++ 是否会为小于 int 的有符号类型调用未定义的行为?

python - 为什么不使用 "is"比较来代替原始类型的 "=="?

c++ - 如何在类中编写高效的正态分布

c++ - 具有模板参数推导和默认模板参数的模板变量

java - 在 Java 中使用引用类型或原始类型是更好的做法吗?

java - Java Collection性能