Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

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

Consider this piece of code:

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

public:
    static const shy object;
};


const shy shy::object = []{
    shy obj;
    obj.dont_touch = 42;   // Accessing a private member; compiles; WHY?
    return obj;
}();


int main()
{
}

Live code (Clang)

Live code (GCC)

It seems really unintuitive to me. What does the C++11/14 standard say about this? Is this a GCC/Clang bug?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 de?nition 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...