Zend certified PHP/Magento developer

Why does the “use of local variable with automatic storage from containing function” error message exist? [migrated]

I have a C++ language/compiler design curiosity question. I’m using gcc 11.2.0 on Cygwin.

Why is it an error to directly reference local variables in structures? Lambda functions do this all the time, and they are basically no different from structures containing the operator() method. As an example:

static inline void
   language_complaint( void )       // Grumble, grumble, grumble
{  printf("nlanguage_complaint...n");

   // Given that this compiles and runs...
   int foo= 22;
   printf("foo: %p->%dn", &foo, foo);
   std::function bar= [foo](void) { printf("foo: %p->%dn", &foo, foo); };
   bar();

#if true // And so does this...
   struct named {
     int const foo;
     named(int foo) : foo(foo) {}   // Use constructor to copy local variable
     void operator()(void) { printf("foo: %p->%dn", &foo, foo); }
   } one(foo);
   one();

// ...And even this, which causes wild stores if improperly used... 
   struct name2 {
     int* const foo;
     name2(int& foo) : foo(&foo) {} // Use constructor to reference local variable
     void operator()(void) { *foo= 42; printf("foo: %p->%dn", foo, *foo); }
   } two(foo);
   two();
   printf("foo: %p->%dn", &foo, foo);

#else // Why, then, is this disallowed?
   struct {
     int /* const */ bar= foo;      // Error: Can't access local variable with auto storage
//   int const foo= ::foo;          // Error: Can't find ::foo. (Probably irrelevant)
     void operator()(void) { printf("bar: %p->%dn", &bar, bar); }
   } one;
   one();
#endif
}

When copying automatic variables for later use, it is easy to step on your own toes, no matter what method you use.

It seems like the language/compiler designers are trying to save you from yourself where plain structures are concerned, but not so much for lambda functions or constructor initialized structures.

Is there some reason for this behavior?