Structured binding violations

1.4k Views Asked by At

The code as follows

#include <tuple>
 
int main() 
{
    auto [a] = std::make_tuple(1);
    return [a]() -> int { return a; }();
}

produces an error in clang 12:

<source>:6:13: error: 'a' in capture list does not name a variable
    return [a]() -> int { return a; }();
<source>:6:34: error: reference to local binding 'a' declared in enclosing function 'main'
    return [a]() -> int { return a; }();

Hovewer both Visual Studio 2019 and gcc 11 with -std=c++20 -Wall -Wextra -pedantic-errors accept it. https://gcc.godbolt.org/z/jbjsnfWfj

So they both still violate the rule that that structured bindings are never names of variables, making them never capturable?

1

There are 1 best solutions below

0
On BEST ANSWER

So they both still violate the rule that that structured bindings are never names of variables, making them never capturable?

No, it is actually clang that is violating the standard, at least for the compiler flags provided. In C++20, the restriction of not directly supporting captures of structured binding aliases has been lifted, allowing them to be directly used without falling back to constructs using init-captures:

Change [expr.prim.lambda.capture]p8 (7.5.5.2) as follows:

If a lambda-expression explicitly captures an entity that is not odr-usable or captures a structured binding (explicitly or implicitly) , the program is ill-formed.