指向成员的指针可以绕开成员的访问级别吗? [英] May pointer to members circumvent the access level of a member?

查看:103
本文介绍了指向成员的指针可以绕开成员的访问级别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们臭名昭著的Lib在如何规避访问检查

Our infamous litb has an interesting article on how to circumvent the access check.

此简单代码充分展示了这一点:

It is fully demonstrated by this simple code:

#include <iostream>

template<typename Tag, typename Tag::type M>
struct Rob { 
  friend typename Tag::type get(Tag) {
    return M;
  }
};

// use
struct A {
  A(int a):a(a) { }
private:
  int a;
};

// tag used to access A::a
struct A_f { 
  typedef int A::*type;
  friend type get(A_f);
};

template struct Rob<A_f, &A::a>;

int main() {
  A a(42);
  std::cout << "proof: " << a.*get(A_f()) << std::endl;
}

编译并运行(输出 42 )和 gcc 4.3.4 gcc 4.5.1 ,gcc 4.7.0(请参阅user1131467的注释),并在 C ++ 03严格模式下使用Clang 3.0和Comeau C / C ++ 4.3.10.1进行编译和MSVC 2005。

Which compiles and runs (output 42) with gcc 4.3.4, gcc 4.5.1, gcc 4.7.0 (see user1131467's comment) and compiles with Clang 3.0 and Comeau C/C++ 4.3.10.1 in C++03 strict mode and MSVC 2005.

我是Luchian在此答案,其中我用它来证明它实际上是合法的。我同意Luchian的说法,这很奇怪,但是Clang和Comeau都是最可用的标准编译器的有力竞争者(默认情况下比MSVC要强得多)...

I was asked by Luchian on this answer in which I used it to justify that it was actually legal. I agree with Luchian that it is weird, however both Clang and Comeau are close contenders for the most "Standard" compilers available (much more so than MSVC by default)...

而且我在现有的标准草案中找不到任何东西(n3337是我接触到的最新版本)。

And I could not find anything in the drafts of the Standards I have available (n3337 being the last version I got my hands on).

所以...可以任何人实际上都证明它是合法吗?

So... can anyone actually justifies that it is legal or not ?

推荐答案

是的,这是合法的。相关文本位于§14.7.2/ 12,其中涉及显式模板实例化:

Yes, it's legal. The relevant text is at §14.7.2/12, talking about explicit template instantiation:


12常用的访问检查规则 do不适用于用于指定显式实例化的名称。 [注意:特别是,函数声明符中使用的模板参数和名称(包括参数类型,返回类型和异常规范)可能是私有类型或对象,通常无法访问这些对象,并且模板可能是通常无法通过
访问的成员模板或成员函数。 — 尾注]

12 The usual access checking rules do not apply to names used to specify explicit instantiations. [ Note: In particular, the template arguments and names used in the function declarator (including parameter types, return types and exception specifications) may be private types or objects which would normally not be accessible and the template may be a member template or member function which would not normally be accessible. — end note ]

Emhpasis矿。

Emhpasis mine.

这篇关于指向成员的指针可以绕开成员的访问级别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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