【问题标题】:reinterpret_cast - the same pointer may have multiple integer representations [duplicate]reinterpret_cast - 同一个指针可能有多个整数表示[重复]
【发布时间】:2020-08-28 14:06:43
【问题描述】:

https://en.cppreference.com/w/cpp/language/reinterpret_cast

转换为足够大小的整数并返回相同指针类型的指针保证具有其原始值,否则无法安全地取消引用生成的指针(相反的往返转换不保证方向;同一个指针可能有多个整数表示)

粗体字是什么意思?

【问题讨论】:

  • 这篇文章是关于演员链pointer -> integer -> pointer。我相信粗体部分意味着你不能做integer -> pointer -> integer。

标签: c++ c++11


【解决方案1】:

声明意味着这是保证的:

int a = 0;
int *p1 = &a;
int *p2 = reinterpret_cast<int *>(reinterpret_cast<std::uintptr_t>(p1));
assert(p1 == p2); // OK

...但这不是:

std::uintptr_t a = 0;
int *b = reinterpret_cast<std::uintptr_t>(reinterpret_cast<int *>(a));
assert(a == b); // Not necessarily true!

【讨论】:

    【解决方案2】:

    这意味着对于一些足够大小的指针类型 P 和整数类型 I,以下成立:

    P p = ...;
    static_assert( p == reinterpret_cast<P>(reinterpret_cast<I>(p) );
    

    但不一定是这样:

    I i = ...;
    static_assert( i == reinterpret_cast<I>(reinterpret_cast<P>(i) );
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 2012-11-05
      • 2015-02-16
      • 2016-12-26
      • 1970-01-01
      相关资源
      最近更新 更多