reinterpret_cast是否保证不更改源指针的地址?

时间:2014-07-09 03:01:45

标签: c++ c casting type-conversion standards

auto p1 = reinterpret_cast<AnyType*>(p_any_other_type);
auto p2 = (AnyType*)(p_any_other_type);

void* p3 = (void*)p_any_other_type;
void* p4 = (void*)p2;

C ++标准保证p1是否始终等于p2

C标准保证p3是否始终等于p4

C标准保证p3是否始终等于p_any_other_type

1 个答案:

答案 0 :(得分:2)

p1!= p2。 (AnyType *)(p)是static_cast&lt; AnyType *&gt;(p)。在多重继承的情况下,static_cast&lt; X *&gt;(y)可以与reinterpret_cast&lt; X *&gt;(y)不同了:

#include <iostream>
using namespace std;

class AnyType { int x; };
class SomeType { int y; };
class OtherType : public SomeType, public AnyType {};

int main(int argc, char **argv) {
    OtherType o;
    OtherType *p_any_other_type = &o;

    auto p1 = reinterpret_cast<AnyType *>(p_any_other_type);
    auto p2 = (AnyType *)(p_any_other_type);

    void *p3 = (void *) p_any_other_type;
    void *p4 = (void *) p2;

    cout << p1 << endl << p2 << endl << p3 << endl << p4 << endl;

    return 0;
}

g++ -Wno-c++11-extensions -o x x.cc警告:

x.cc:12:15: warning: 'reinterpret_cast' from class 'OtherType *' to its base at
      non-zero offset 'AnyType *' behaves differently from 'static_cast'
      [-Wreinterpret-base-class]
    auto p1 = reinterpret_cast<AnyType *>(p_any_other_type);
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
x.cc:12:15: note: use 'static_cast' to adjust the pointer correctly while upcasting
    auto p1 = reinterpret_cast<AnyType *>(p_any_other_type);
              ^~~~~~~~~~~~~~~~
              static_cast
1 warning generated.

运行:

0x7fff5e4c38f8
0x7fff5e4c38fc
0x7fff5e4c38f8
0x7fff5e4c38fc

由于p2!= p1,p3!= p4。