interpret_cast/static_cast和未定义的行为

reinterpret_cast / static_cast and undefined behavior

本文关键字:cast 未定义 static interpret      更新时间:2023-10-16

在一个变体类中,我正在处理的原始存储是一个char数组:

alignas(/* the strictest alignment of all types of the variant */)
char storage[/* ... */];

赋值运算符类似于:

template<class X>
void operator=(const X &x)
{
  // ...code for clearing the storage and setting the tag for type X...
  new(storage) X(x);
}

而获取存储对象的代码是:

template<class X>
const X &get()
{
  // ...
  return *reinterpret_cast<X *>(storage);
  // ...
}

它似乎有效,但它总是定义得很好吗?我担心安全地取消引用指针(类型别名规则允许这样做吗?)。

当前的实施与之间有什么区别吗

 return *static_cast<const X *>(static_cast<const void *>(storage));

相关问题/答案:

https://stackoverflow.com/a/7321815/3235496(见詹姆斯·坎泽的评论)。


编辑

第二个问题在这里已经有了答案:C++我们什么时候应该更喜欢使用双链static_cast而不是repret_cast

由于storage正确对齐,我无法想象哪里会出现问题。关于指针转换的第(*)4.10段说:类型为"pointer to cv T"的prvalue,其中T是对象类型,可以转换为类型为"指针to cv void"的prvalue。将指向对象类型的指针的非null指针值转换为"指向cv void的指针"的结果表示内存中与原始指针值相同字节的地址

关于你的第二个问题,第5.2.10段在reinterpres_cast:对象指针可以显式转换为不同类型的对象指针。当对象指针类型的prvalue v转换为对象指针类型"pointer to cv T"时,结果为static_cast<cv T*>(static_cast<cv void*>(v)),其中cv代表可选的constvolatile

所以这部分是有保证的规格。正如我们所看到的,void *的强制转换应该指向内存的第一个字节,对于我对标准的理解来说,没有UB。。。前提是编译器具有相同的理解;-)

(*)参考:当前C++规范的草案