Reputation: 4579
Consider the following code:
struct S
{
int x;
void f()
{
auto l = [&](){ x = 42; }; //this is implicitly captured here
}
};
§5.1.2/14 states:
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 &.
Hence I conclude, that this
is not captured by copy. But then by §5.1.2/15:
An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy. It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference.
this
is captured by reference. But now §5.1.2/17 states:
[...] If
this
is captured, each odr-use ofthis
is transformed into an access to the corresponding unnamed data member of the closure type, [...]
As far as I understand, this implies that there must be an unnamed data member in the closure type corresponding to the this
pointer. But since this
is captured by reference the standard doesn't demand that such a member exists. What do I get wrong?
Upvotes: 6
Views: 303
Reputation: 283664
Of course such a data member exists in the closure type. Capture by value and capture by reference both require a data member in the closure type. The only question is its type:
T /* maybe const and/or volatile */ * captured_this;
vs
T /* maybe const and/or volatile */ * const & captured_this;
Since this
can't ever change, there is no observable difference between the two.
Upvotes: 0
Reputation: 42554
The standard does a poor job of making it clear, but this
can only be captured by copy. It could not possibly be captured by lvalue-reference since this
is an rvalue per C++11 §9.3.2/1.
Note that the standard forbids explicitly capturing this
by reference since (a) the grammar does not allow &this
in a capture list since this
is lexically a keyword and not an identifier, and (b) 5.1.2/8 forbids explicit capture of this
when the capture-default is =
.
It would seem to be an error in the specification that this
can be implicitly captured when the capture-default is &
, suggesting that it is captured by reference.
Upvotes: 1
Reputation: 446
I think you've found a specification bug - you're correct in that this
is being captured by reference, but the text you found in §5.1.2/17 should only apply if this
is captured by copy.
As Casey says though, it doesn't really make much sense to capture this
by reference.
Upvotes: 0