【发布时间】:2012-04-12 00:49:41
【问题描述】:
我们臭名昭著的 litb 在how to circumvent the access check 上有一篇有趣的文章。
这个简单的代码就充分展示了:
#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;
}
使用gcc 4.3.4、gcc 4.5.1、gcc 4.7.0(请参阅 user1131467 的评论)编译和运行(输出 42)并在 C+ 中使用 Clang 3.0 和 Comeau C/C++ 4.3.10.1 编译+03 严格模式和 MSVC 2005。
Luchian 在this answer 上问我,我用它来证明它实际上是合法的。我同意 Luchian 的说法,这很奇怪,但是 Clang 和 Comeau 都是可用的最“标准”编译器的有力竞争者(默认情况下比 MSVC 更多)...
我在可用的标准草案中找不到任何内容(n3337 是我得到的最后一个版本)。
那么...任何人都可以证明它合法与否吗?
【问题讨论】:
-
仅供参考,这会在
-std=c++11和-std=gnu++11中输出proof:42和g++-4.7 (Debian 4.7.0-1) 4.7.0 -
对不起,这是我的错。这确实编译,没有编译的是stackoverflow.com/a/6886432/673730 - 我试图访问一个私有函数,而不是数据成员。
-
顺便说一句,我仍在寻找答案,如果答案有效,那将正是我一直在寻找的,但事实并非如此。
-
@LuchianGrigore:没问题,感谢您纠正问题。
-
@user1131467:感谢测试。
标签: c++ c++11 standards-compliance