Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structured binding violations

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?

like image 689
Fedor Avatar asked Jun 08 '21 08:06

Fedor


Video Answer


1 Answers

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.

like image 128
Jodocus Avatar answered Oct 19 '22 13:10

Jodocus