通过指向成员的指针访问不存在的成员

当通过指向成员的指针访问对象的非静态成员时,如果该对象实际上不包含指针所表示的成员,则行为是未定义的。 (这样的成员指针可以通过 static_cast 获得。)

struct Base { int x; };
struct Derived : Base { int y; };
int Derived::*pdy = &Derived::y;
int Base::*pby = static_cast<int Base::*>(pdy);

Base* b1 = new Derived;
b1->*pby = 42; // ok; sets y in Derived object to 42
Base* b2 = new Base;
b2->*pby = 42; // undefined; there is no y member in Base