Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I believe clang erroneously allows inline friend function access to data in an enclosing scope. Both gcc and vs2013 reject this code

The friend function f doesn't have access to a private member of the enclosing 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();
}

At least, this is what I think [class.nest]/4 in N4140 is saying (see below).

§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

like image 804
Belloc Avatar asked Jul 19 '15 17:07

Belloc


1 Answers

I believe that you are correct, in that both Visual Studio and GCC correctly reject the code based on the spec you cited. Clang appears to be in error by allowing access to A's private member variable p from the friend function f(), because f() is a friend of B, not A.

For a good discussion of the scope of friend functions, see the top-voted answer in the following SO post: What's the scope of inline friend functions

like image 67
rholmes Avatar answered Sep 20 '22 07:09

rholmes