指针如何引用不同的类型

How can a pointer refer to a different type?

本文关键字:类型 引用 何引用 指针      更新时间:2023-10-16

(4.1/1( 如果左值所指的对象不是 类型 T 并且不是派生自 T 类型的对象,或者如果该对象 未初始化,需要此转换的程序具有 未定义的行为。

由此,我假设

struct B {
     int x; };
B *p;
*p; //undefined behavior

*p 是一个左值,指的是未初始化的对象。它如何引用不是"B"类型或其派生类型的对象?我是不是误会了什么?

简单:

int n = 5;
double * p = reinterpret_cast<double*>(&n);
*p += 1.0; // undefined behaviour: p points to an int, not a double
++*reinterpret_cast<int*>(p);  // legal; pointer can be cast back-and-forth

不太容易:

union bogus { int * a; double * b; } B;
int n;
B.a = &n;
*B.b += 1.0; // undefined behaviour

常见的 C 陷阱(不产生诊断!

void do_a(void * p) { ++*reinterpret_cast<int*>(p); }
void do_b(void * p) { *reinterpret_cast<double*>(p) += 1.0; }
int main() { int n = 4; do_b(&n); /* eek */ }

简单。

 int i;
 B *p;
 p = (B*)&i;

做。

使它指向不属于对象 T 或派生类型的内容的一种方法是使用指针强制转换键入双关语:

struct A{ int x; };
struct B{ float x; };

A x;
B *p = (B*)&x;
*p;  //  Undefined behavior

在此示例中,指针p未指向类型 B 的内容。它指向不兼容的 A 类内容。

请注意,此示例还违反了严格别名 - 这也是未定义的行为。