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
#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/