gpt4 book ai didi

c++ - 为什么 reinterpret_cast 不强制 copy_n 用于相同大小类型之间的转换?

转载 作者:太空狗 更新时间:2023-10-29 20:58:04 24 4
gpt4 key购买 nike

根据 cppreference.com , reinterpret_cast:

Converts between types by reinterpreting the underlying bit pattern.

但是等等,这是个谎言,因为它只在这些情况下有效:

When a pointer or reference to object of type T1 is reinterpret_cast (or C-style cast) to a pointer or reference to object of a different type T2, the cast always succeeds, but the resulting pointer or reference may only be accessed if both T1 and T2 are standard-layout types and one of the following is true:

  • T2 is the (possibly cv-qualified) dynamic type of the object
  • T2 and T1 are both (possibly multi-level, possibly cv-qualified at each level) pointers to the same type T3
  • T2 is the (possibly cv-qualified) signed or unsigned variant of the dynamic type of the object
  • T2 is an aggregate type or a union type which holds one of the aforementioned types as an element or non-static member (including, recursively, elements of subaggregates and non-static data members of the contained unions): this makes it safe to cast from the first member of a struct and from an element of a union to the struct/union that contains it.
  • T2 is a (possibly cv-qualified) base class of the dynamic type of the object
  • T2 is char or unsigned char

根据该列表,一个非法示例是:

auto foo = 13LL;
auto bar = reinterpret_cast<double&>(foo);

所以唯一可以接受的方式就是复制内存:

auto foo = 13LL;
double bar;

copy_n(reinterpret_cast<char*>(&foo), sizeof(foo), reinterpret_cast<char*>(&bar));

我的问题是,为什么 reinterpret_cast 不为我处理这个问题?还是有其他可用的东西,这样我就不必跳过这个圈套了?

最佳答案

why doesn't reinterpret_cast handle that for me?

一个原因是未指定大小、对齐方式和位表示,因此此类转换不可移植。但是,这并不能真正证明使行为未定义,而只是实现定义是合理的。

通过将其设为未定义,允许编译器假定不相关类型的表达式不会访问同一对象,这样可以实现更好的优化。例如,在下面:

int   & i = something();
float & f = something_else();

const int i1 = i;
f = 42;
const int i2 = i;

编译器可以假定 i1i2 都具有相同的值(i 被赋值给 f), 并将它们优化为一个常量。打破假设将导致未定义的行为。

Or is there something else available so I don't have to jump through this hoop?

复制字节是将一种对象类型重新解释为不相关类型的唯一明确定义的方法。

使用 reinterpret_cast 或 union 进行别名有时可能会起作用(假设大小等匹配),但如果优化器对未定义的行为过于聪明,则可能会误导您。

关于c++ - 为什么 reinterpret_cast 不强制 copy_n 用于相同大小类型之间的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28697626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com