p2rkw
p2rkw

Reputation: 452

Can inline lambda initializer capture 'this' pointer?

Can inline member initialization lambda capture and use this pointer?

struct A{
  int a = 42;
  int b = [this](){
    return this->a * 4;
  }();
};

Is it valid C++11 code (according to specification) or is it just a GCC extension?

If it is valid, why do I have to use this-> when referring to member a?

Upvotes: 20

Views: 824

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

Is it valid c++11 code?

No. Only lambdas in block scope can have capture lists:

C++11 5.1.2/9 A lambda-expression whose smallest enclosing scope is a block scope is a local lambda expression; any other lambda-expression shall not have a capture-list in its lambda-introducer.

So it seems this is a GCC extension. (As noted in the comments, this is an open issue, so might well become standard one day.)

why I have to use this-> while referring to member a?

You don't, at least with the version of GCC I'm using: http://ideone.com/K857VC.

Upvotes: 16

Related Questions