c++ - 我相信 clang 错误地允许内联友元函数访问封闭范围内的数据。 gcc 和 vs2013 都拒绝此代码

标签 c++ clang c++14 friend clang++

友元函数 f 无权访问封闭类 A 的私有(private)成员。

#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.

live example

最佳答案

我相信您是正确的,因为 Visual Studio 和 GCC 根据您引用的规范正确拒绝了代码。通过允许从友元函数 f() 访问 A 的私有(private)成员变量 p,Clang 似乎出错了,因为 f()B 的 friend ,而不是 A

有关友元函数范围的良好讨论,请参阅以下 SO 帖子中投票最多的答案:What's the scope of inline friend functions

关于c++ - 我相信 clang 错误地允许内联友元函数访问封闭范围内的数据。 gcc 和 vs2013 都拒绝此代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31504163/

相关文章:

gcc - GCC/Clang 的 -framework 选项在 Linux 上工作吗?

c++ - 外部模板 'inconsistent explicit instantiations'

C++ Boost Regex 不保存捕获

c++ - 为 Arduino 编写库

RubyMotion 错误 : clang Segmentation fault: 11

c++ - 使用 sfinae 检测可变参数模板的基类是否具有特定方法

c++ - 使用 SFINAE 启用基于包大小的部分特化

c++ - 编辑控件未完全使用所选画笔重新绘制

c++ - 如何处理代码中的数据库凭据

clang 无法独立解析我的 .h 文件