Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the this pointer captured?

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 of this 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?

like image 637
MWid Avatar asked Jan 14 '14 16:01

MWid


1 Answers

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.

like image 181
Casey Avatar answered Sep 30 '22 18:09

Casey