结构化绑定违规

Structured binding violations

代码如下

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

在 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 Visual Studio 2019 和 gcc 11 with -std=c++20 -Wall -Wextra -pedantic-errors 接受它。 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?

不,实际上是 clang 违反了标准,至少对于提供的编译器标志而言。 在C++20中,不直接支持捕获结构化绑定别名的限制has been lifted,允许直接使用它们而无需回退到使用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.