Structured binding violations
Asked Answered
B

1

9

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?

Bolanger answered 8/6, 2021 at 8:2 Comment(0)
S
8

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.

Staw answered 8/6, 2021 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.