lambda-capture by reference 中的 this 指针
this pointer in lambda-capture by reference
struct CL
{
int i;
void fnc()
{
[&this](){i=1;}; // (1) error
[&](){i=1;}; // (2) ok
}
};
第一种情况无效,但第二种情况有效。这是为什么?
我看到标准 5.1.2/1:
capture:
identifier
& identifier
this
(即 &this 不存在)
和 5.1.2/15:
An entity is captured by reference if it is implicitly or explicitly
captured but not captured by copy
在第二种情况下 "this" 未根据 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 &
但是我怎样才能通过值 显式 捕获 "this" 指针?或者只能隐含地使用 default-capture & ?
形式上,[&]
确实通过引用捕获了 this
,根据 5.1.2/16 "An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy." 但这并不重要, 因为
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]
因此对于this
,复制捕获和引用捕获是无法区分的。出于所有实际目的,this
始终由副本捕获。
struct CL
{
int i;
void fnc()
{
[&this](){i=1;}; // (1) error
[&](){i=1;}; // (2) ok
}
};
第一种情况无效,但第二种情况有效。这是为什么?
我看到标准 5.1.2/1:
capture:
identifier
& identifier
this
(即 &this 不存在)
和 5.1.2/15:
An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy
在第二种情况下 "this" 未根据 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 &
但是我怎样才能通过值 显式 捕获 "this" 指针?或者只能隐含地使用 default-capture & ?
形式上,[&]
确实通过引用捕获了 this
,根据 5.1.2/16 "An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy." 但这并不重要, 因为
5.1.2/18 ... If
this
is captured, each odr-use ofthis
is transformed into an access to the corresponding unnamed data member of the closure type, cast (5.4) to the type ofthis
. [Note: The cast ensures that the transformed expression is a prvalue. —end note]
因此对于this
,复制捕获和引用捕获是无法区分的。出于所有实际目的,this
始终由副本捕获。