绕过继承和函数指针保护

Bypassing protected with inheritance and function pointer

我见过几次使用以下模式来访问受保护的成员函数。

class A{
public:
    virtual ~A(){};
protected:
        void foo(){}
};

class B : public A{};


class Hacky : public B{
public:
    using B::foo;
};

int main(){
    B b;
    A& a = b;
    auto ptr = &Hacky::foo;
    (a.*ptr)();
}

我认为这是 this page 之后的未定义行为,内置指向成员的指针访问运算符,第 5 点(这里 E1 动态类型是 B,它不包含 Hacky::foo ),但我不是 100% 确定。有人可以对此给出明确的答案吗?

type of ptrvoid (A::*)(),不是void (Hacky::*)(),所以没问题。