通过成员指针访问受保护的成员:这是黑客吗? [英] Access to protected member through member-pointer: is it a hack?

查看:121
本文介绍了通过成员指针访问受保护的成员:这是黑客吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道只能从派生类自己的实例访问从基类中指定的protected成员.这是标准中的一项功能,并且已经在Stack Overflow上进行了多次讨论:

We all know members specified protected from a base class can only be accessed from a derived class own instance. This is a feature from the Standard, and this has been discussed on Stack Overflow multiple times:

  • 无法从派生类型的作用域访问另一个实例的受保护成员 ;
  • 为什么我的对象无法访问在公共基类中定义的另一个对象的受保护成员?
  • 还有其他人.

但是似乎有可能绕过成员指针的限制,因为用户chtz 具有给我看了:

But it seems possible to walk around this restriction with member pointers, as user chtz has shown me:

struct Base { protected: int value; };
struct Derived : Base
{
    void f(Base const& other)
    {
        //int n = other.value; // error: 'int Base::value' is protected within this context
        int n = other.*(&Derived::value); // ok??? why?
        (void) n;
    }
};

在大肠杆菌上进行实时演示

为什么会这样,这是实现标准中的通俗易懂的功能还是出现故障?

Why is this possible, is it a wanted feature or a glitch somewhere in the implementation or the wording of the Standard?

从评论中出现了另一个问题:如果用实际的Base调用Derived::f ,这是不确定的行为吗?

From comments emerged another question: if Derived::f is called with an actual Base, is it undefined behaviour?

推荐答案

使用 class成员访问权限无法访问成员的事实

The fact that a member is not accessible using class member access expr.ref (aclass.amember) due to access control [class.access] does not make this member inaccessible using other expressions.

表达式&Derived::value (其类型为int Base::*)完全符合标准,它指定Base的成员value.然后,表达式a_base.*p(其中p是指向Base的成员的指针,而a_baseBase的实例的指针)也是

The expression &Derived::value (whose type is int Base::*) is perfectly standard compliant, and it designates the member value of Base. Then the expression a_base.*p where p is a pointer to a member of Base and a_base an instance of Base is also standard compliant.

因此,任何符合标准的编译器都应使表达式other.*(&Derived::value);定义为行为:访问other的成员value.

So any standard compliant compiler shall make the expression other.*(&Derived::value); defined behavior: access the member value of other.

这篇关于通过成员指针访问受保护的成员:这是黑客吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆