C++11 lambdas can access my private members. Why?

后端 未结 1 1289
日久生厌
日久生厌 2020-12-09 03:05

Consider this piece of code:

class shy {
private:
    int dont_touch;    // Private member

public:
    static const shy object;
};


const shy shy::object =         


        
相关标签:
1条回答
  • 2020-12-09 03:59

    As already answered in the comments @Tony D and @dyp:

    § 9.4.2/2 Static data members [class.static.data]:

    The initializer expression in the definition of a static data member is in the scope of its class.

    The above means that static data members and their initializers can access other private and protected members of their class.

    Also consdering the standard § 5.1.2/2&3 Lambda expressions [expr.prim.lambda]:

    2 The evaluation of a lambda-expression results in a prvalue temporary (12.2). This temporary is called the closure object. A lambda-expression shall not appear in an unevaluated operand (Clause 5). [ Note: A closure object behaves like a function object (20.9).-end note]

    3 The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type - called the closure type - whose properties are described below. This class type is not an aggregate (8.5.1). The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression.

    Combining the above we end up to the conclusion that the prvalue temporary closure object of your lambda is declared and defined in the initializer of the static const data member shy::object and consequently the scope of the lambda's closure object is the scope of class shy. As such it can access private members of class shy.

    0 讨论(0)
提交回复
热议问题