当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - this pointer in lambda-capture by reference

问题描述:

struct CL

{

int i;

void fnc()

{

[&this](){i=1;}; // (1) error

[&](){i=1;}; // (2) ok

}

};

Here is 1st case which doesn't work, but second case does. Why is that?

I see Standard 5.1.2/1:

capture:

identifier

& identifier

this

(i.e. &this doesn't exist)

And 5.1.2/15:

An entity is captured by reference if it is implicitly or explicitly

captured but not captured by copy

In second case "this" doesn't captured by copy according 5.1.2/14:

An entity is captured by copy if it is implicitly captured and the

capture-default is = or if it is explicitly captured with a capture

that does not include an &

But how can I capture "this" pointer by value explicitly? Or is it possible only implicitly with default-capture & ?

网友答案:

Formally, [&] does indeed capture this by reference, per 5.1.2/16 "An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy." But that doesn't matter, because

5.1.2/18 ... If this is captured, each odr-use of this is transformed into an access to the corresponding unnamed data member of the closure type, cast (5.4) to the type of this. [Note: The cast ensures that the transformed expression is a prvalue. —end note]

So for this, capture-by-copy and capture-by-reference are indistinguishable. For all practical purposes, this is always captured by copy.

分享给朋友:
您可能感兴趣的文章:
随机阅读: