public inbox for gcc-patches@gcc.gnu.org
 help / color / mirror / Atom feed
* lambda capture scope question
@ 2017-01-18 14:46 Nathan Sidwell
  0 siblings, 0 replies; only message in thread
From: Nathan Sidwell @ 2017-01-18 14:46 UTC (permalink / raw)
  To: Jason Merrill; +Cc: GCC Patches

[-- Attachment #1: Type: text/plain, Size: 1214 bytes --]

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

[-- Attachment #2: capture.cc --]
[-- Type: text/x-c++src, Size: 499 bytes --]

#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;
}

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2017-01-18 14:45 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2017-01-18 14:46 lambda capture scope question Nathan Sidwell

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).