将对象作为错误类型访问

在大多数情况下,访问一种类型的对象是非法的,就好像它是一种不同的类型(忽略 cv 限定符)。例:

float x = 42;
int y = reinterpret_cast<int&>(x);

结果是未定义的行为。

严格别名规则有一些例外 :

  • 可以访问类类型的对象,就好像它是一个类型是实际类类型的基类。
  • 任何类型都可以作为 charunsigned char 访问,但反之则不然:无法访问 char 数组,就好像它是任意类型一样。
  • 有符号整数类型可以作为相应的无符号类型访问,反之亦然

一个相关的规则是,如果在一个实际上与函数的定义类或派生类没有相同类型的对象上调用非静态成员函数,则会发生未定义的行为。即使函数不访问对象,也是如此。

struct Base {
};
struct Derived : Base {
    void f() {}
};
struct Unrelated {};
Unrelated u;
Derived& r1 = reinterpret_cast<Derived&>(u); // ok
r1.f();                                      // UB
Base b;
Derived& r2 = reinterpret_cast<Derived&>(b); // ok
r2.f();                                      // UB