结构化绑定违规

Fed*_*dor 6 c++ stdtuple structured-bindings c++20

代码如下

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

在 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; }();
Run Code Online (Sandbox Code Playgroud)

然而,Visual Studio 2019 和 gcc 11 都-std=c++20 -Wall -Wextra -pedantic-errors接受它。https://gcc.godbolt.org/z/jbjsnfWfj

所以它们仍然违反了结构化绑定永远不是变量名称的规则,使它们永远无法捕获?

Jod*_*cus 5

所以它们仍然违反了结构化绑定永远不是变量名称的规则,使它们永远无法捕获?

不,实际上是 clang 违反了标准,至少对于提供的编译器标志。在 C++20 中,取消了不直接支持捕获结构化绑定别名的限制,允许直接使用它们而无需回退到使用 init-captures 的构造:

更改 [expr.prim.lambda.capture]p8 (7.5.5.2) 如下:

如果 lambda 表达式显式捕获了一个不可 odr 可用的实体或捕获了结构化绑定(显式或隐式) ,则程序格式错误。