Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can inline lambda initializer capture 'this' pointer?

Tags:

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?

like image 956
p2rkw Avatar asked Sep 19 '14 12:09

p2rkw


1 Answers

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.

like image 134
Mike Seymour Avatar answered Oct 21 '22 16:10

Mike Seymour