将int放入char数组是否合法地需要重新放置? [英] Is placement new legally required for putting an int into a char array?

查看:151
本文介绍了将int放入char数组是否合法地需要重新放置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎已经达成共识,由于C ++别名规则,您不能随意将一个int *指向一个char数组.

There seems to be some agreement that you can't willy nilly point (an int*) into a char array because of the C++ aliasing rules.

从另一个问题开始-通用char [基于]的存储,并避免了严格混淆的相关UB -似乎允许通过放置新的(重新)使用存储.

From this other question -- Generic char[] based storage and avoiding strict-aliasing related UB -- it seems that it is allowed to (re-)use storage through 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 ++是 ,实际上是需要使其成为合法的新展示位置吗?

So, is the above legal C++ and is the placement new actually needed to make it legal?

推荐答案

是的,必须放置new,否则您将违反严格的别名(分配为

Yes, the placement new is necessary, otherwise you'd violate strict aliasing (assignment is access).

以上法律合法吗?几乎可以(尽管它几乎可以在所有实现中使用).您通过强制转换创建的指针未指向该对象,因为(已销毁的)数组和int对象不是

Is the above legal? Almost (although it will work on virtually all implementations). The pointer you've created through the cast does not point to the object, because the (now destroyed) array and the int object are not pointer-interconvertible; use std::launder((int*)buf), or better yet, use the placement new's return value.

这篇关于将int放入char数组是否合法地需要重新放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆