【问题标题】:Issue in reinterpret_castreinterpret_cast 中的问题
【发布时间】:2021-10-26 05:55:06
【问题描述】:
struct A
{
   uint8_t hello[3]; 
};

struct B
{
    const struct C* hello;
};

struct C
{
    uint8_t hi[3];
};

B.hello = &reinterpret_cast<C &>(A);

假设我已经用值123 填充了结构A。 如果我打印B.hello.hi[0],我会得到0。相反,我应该得到1。 我是不是选错了?

我检查了代码中reinterpret_cast 行正上方的struct A 的值,它打印正常,所以我认为将值存储在A 中没有任何问题。这只是导致问题的转换。

【问题讨论】:

  • 相反,我应该得到 1 - 为什么?看看reinterpret_cast 可以做的list of valid conversions 并思考哪个项目符号适用于您正在尝试做的事情。

标签: c++ reinterpret-cast


【解决方案1】:

强制转换适用于实例而不是类,因此您需要强制转换 A 的实例而不是 A 本身

#include <cstdint>
#include <cassert>

struct A
{
    uint8_t hello[3];
};

struct B
{
    const struct C* hello;
};

struct C
{
    uint8_t hi[3];
};


int main()
{
    A a{}; 
    a.hello[0] = 1;
    a.hello[1] = 2;
    a.hello[2] = 3;

    B b{};
    b.hello = reinterpret_cast<C*>(&a);
    auto hi = b.hello->hi;
    assert(hi[2] == 3);
}

【讨论】:

  • 这纯粹是未定义的行为。 What is the strict aliasing rule?
  • 我同意它是未定义的。我也不会这样做,但问题是关于演员的。如果写这样的代码很聪明(事实并非如此),那就不是了。 ;)
猜你喜欢
  • 1970-01-01
  • 2010-12-24
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 2011-06-17
相关资源
最近更新 更多