gpt4 book ai didi

c++ - "Capture by move"不阻止引用捕获

转载 作者:行者123 更新时间:2023-12-04 01:08:39 28 4
gpt4 key购买 nike

当我写 [&,x](){ /* making use of x */ } , x被值(value)捕获。
当我写 [=,&x](){ /* making use of x */ } , x通过引用捕获。
如果我尝试写 [&x, x](){ … }我收到一条错误消息,告诉我 x在捕获列表中只能出现一次。
然而,[&x, y = std::move(x)](){ /* making use of x and y */ }();编译正常,但出现段错误。
为什么代码甚至可以编译?为什么标准允许我通过引用捕获变量,并且我还在“通过移动捕获”初始化捕获中使用它?

最佳答案

案例[&x, y = std::move(x)](){ };从编译器的角度来看是相当合法的,因为不同的标识符用于捕获。该标准说明如下:
[expr.prim.lambda/capture-2]

Ignoring appearances in initializers of init-captures, an identifier or this shall not appear more than once in a lambda-capture.

[&i, a = i]{ };    // OK
[&i, a = std::move(i)]{ }; // OK

[&i, i]{ }; // error: i repeat
[&i, i = std::move(i)]{ }; // error: i repeated

关于c++ - "Capture by move"不阻止引用捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65517730/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com