This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

lambda capture scope question


Jason,
What is the scope of a lambda capture? AFAICT it depends on whether the capture is simple or initialized.

the attached program prints:
[x] is i
[x=x] is i
[x=x] {short x;} is s

I'm not sure that's right.

The clearest one is an initialized capture. [5.1.6]/12 says this is equivalent to 'auto VAR = INIT;' 'whose declarative region is the lambda-expression's compound statement'. So it looks like '[x=x] is i' is right -- we're hiding the lambda's parameter 'x'.

but, if that's the case, is the 3rd one well formed? Should it be treated as an ill-formed redefinition of 'x' in a single scope? We're behaving as-if there's an additional scope just outside the compound statement.

For a simple capture nothing appears mentioned about any scope for the capture. We seem to be injecting it just the same as for an initialized capture, and therefore hiding the parameter.

IMHO having the scoping rules be different for simple and initialized captures is confusing. I understand Clang behaves differently for this example, apparently making the parameter 'x' visible inside the lambda. (I have not confirmed that myself)

Perhaps the std wording needs clarifing?

nathan

--
Nathan Sidwell
#include <typeinfo>
extern "C" int printf (char const *, ...);

int main ()
{
  int x = 5;
  auto lam_1 = [x] (float x) 
    {
      return typeid(x).name ();
    };

  printf ("[x] is %s\n", lam_1 (5.0f));

  auto lam_2 = [x = x] (float x)
    {
      return typeid(x).name ();
    };
  
  printf ("[x=x] is %s\n", lam_2 (5.0f));

  auto lam_3 = [x = x] (float x)
    {
      short x = 4;
      return typeid(x).name ();
    };
  printf ("[x=x] {short x;} is %s\n", lam_3 (5.0f));
  
  return 0;
}

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]