我相信 clang 错误地允许内联友元函数访问封闭范围内的数据。 gcc 和 vs2013 都拒绝此代码
I believe clang erroneously allows inline friend function access to data in an enclosing scope. Both gcc and vs2013 reject this code
友元函数 f
无法访问封闭 class A
.
的私有成员
#include <iostream>
class A{
const static int p = 1;
class B {
friend void f() {
std::cout << p << '\n';
std::cout << q << '\n';
}
};
public:
const static int q = 2;
};
void f();
int main()
{
f();
}
至少,这就是我认为 N4140 中的 [class.nest]/4 所说的(见下文)。
§9.7/4
Like a member function, a friend function (11.3) defined within a
nested class is in the lexical scope of that class; it obeys the same
rules for name binding as a static member function of that class
(9.4), but it has no special access rights to members of an enclosing
class.
我相信你是对的,因为 Visual Studio 和 GCC 都正确地拒绝了基于你引用的规范的代码。 Clang 似乎错误地允许从友元函数 f()
访问 A
的私有成员变量 p
,因为 f()
是 B
的友元, 不是 A
.
有关好友功能范围的良好讨论,请参阅以下 SO post 中投票最高的答案:What's the scope of inline friend functions
友元函数 f
无法访问封闭 class A
.
#include <iostream>
class A{
const static int p = 1;
class B {
friend void f() {
std::cout << p << '\n';
std::cout << q << '\n';
}
};
public:
const static int q = 2;
};
void f();
int main()
{
f();
}
至少,这就是我认为 N4140 中的 [class.nest]/4 所说的(见下文)。
§9.7/4
Like a member function, a friend function (11.3) defined within a nested class is in the lexical scope of that class; it obeys the same rules for name binding as a static member function of that class (9.4), but it has no special access rights to members of an enclosing class.
我相信你是对的,因为 Visual Studio 和 GCC 都正确地拒绝了基于你引用的规范的代码。 Clang 似乎错误地允许从友元函数 f()
访问 A
的私有成员变量 p
,因为 f()
是 B
的友元, 不是 A
.
有关好友功能范围的良好讨论,请参阅以下 SO post 中投票最高的答案:What's the scope of inline friend functions