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

标签 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

最佳答案

p1 != p2。 (AnyType *)(p) 是 static_cast(p)。在多重继承的情况下,static_cast(y) 可以与 reinterpret_cast(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。

关于c++ - reinterpret_cast 是否保证不更改源指针的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644728/

相关文章:

c - 从内存缓冲区读取结构会引发编译器错误和段错误

c++ - 条件运算符总是可以被 if/else 替换吗?

c - 字符集/位串的减法运算

c - 如何对这些结构进行编程?

c - 错误 : expected expression before 'unsigned'

python - "a//b"和 "int(a/b)"之间的区别

c++ - 数组索引错误

c++ - release() 未声明为 c++

c++ - CouchDB UTF-8 字符错误

Angular HttpClient 方法不转换响应类型