gpt4 book ai didi

C++11 lambda 可以访问我的私有(private)成员。为什么?

转载 作者:太空狗 更新时间:2023-10-29 23:10:29 25 4
gpt4 key购买 nike

考虑这段代码:

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)

这对我来说似乎真的很不直观。 C++11/14 标准对此有何规定?这是 GCC/Clang 错误吗?

最佳答案

正如评论中已经回答的那样 @Tony D@dyp :

§ 9.4.2/2 静态数据成员 [class.static.data]:

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

上面的意思是static数据成员及其初始化程序可以访问其他 privateprotected他们类(class)的成员。

同时考虑标准 § 5.1.2/2&3 Lambda 表达式 [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.

综合以上我们得出的结论是你的 lambda 的纯右值临时闭包对象是在 static 的初始化程序中声明和定义的 const数据成员shy::object因此 lambda 的闭包对象的范围是 class shy 的范围. 因此它可以访问 class shy 的私有(private)成员.

关于C++11 lambda 可以访问我的私有(private)成员。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57495363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com