C ++ 11 lambdas可以访问我的私有成员。为什么? [英] C++11 lambdas can access my private members. Why?

查看:101
本文介绍了C ++ 11 lambdas可以访问我的私有成员。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这段代码:

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()
{
}

即时代码(Clang)

直播代码(GCC)

似乎真的不直接对我。 C ++ 11/14标准对此说了什么?这是一个GCC / Clang错误?

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

推荐答案

正如在 @ Tony D @dyp

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

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


static 数据成员的
定义中的初始化表达式在其类的范围内。

上述意味着 static 数据成员及其初始化器可以访问其他 private protected

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


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]

code> lambda表达式的类型(也是闭包对象的类型)是一种唯一的未命名非单元类类型 - 称为闭包类型,其属性如下所述。此类类型不是聚合(8.5.1)。闭包类型在包含相应lambda表达式的最小块范围,类范围或命名空间范围中声明。

结合上述,我们得出结论:您的lambda的prvalue临时闭包对象在 static 的初始化器中声明和定义。 const 数据成员 shy :: object ,因此 lambda关闭对象的范围是 class shy 因此可以访问 class shy 的私有成员。

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.

这篇关于C ++ 11 lambdas可以访问我的私有成员。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆