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

标签 c++ gcc c++11 lambda clang

考虑这段代码:

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/

相关文章:

c++ - "auto"变成了错误的类型?

c++ - cygwin : sometimes unix style paths 上的 gcc -MM

c++ - Win32 滚动条 "slop distance"常量?

C++运算符重载解析歧义

linux - Linux 内核 2.6 编译期间丢失系统调用错误

c++ - 将 chrono::milliseconds 转换为 uint64_t?

c++ - 使用 "new ClassType(std::move(/*class_object*/))"在 freestore 中构建对象

c++ - MSVC std::_Pad 无虚拟析构函数

接受任何类型的函数作为参数的 C++ 类

c++ - 未定义行为的定义