尝试编译以下代码:
#include <functional>
void test() {
int a = 5;
std::function<void()> f = [a](){
[a]()mutable{ // isn't it capture 'a' by copy???
a = 13; // error: assignment of read-only variable 'a'
}();
};
}
出现了“error: assignment of read-only variable 'a'”错误。
通过在捕获变量a
时添加花括号来更改代码:
#include <functional>
void test() {
int a = 5;
std::function<void()> f = [a](){
[a{a}]()mutable{ // this explicitly copies a
a = 13; // error: assignment of read-only variable ‘a’
}();
};
}
消除了编译错误。
我想知道为什么会这样?第一个变量不是等同于第二个吗?
这是在使用Debian版本的g++
8.3.0时发生的。
clang++
版本7.0.1可以成功编译它。
g++
存在缺陷吗?
a
是局部的吗?全局的吗? - StoryTeller - Unslander Monicaa
局部变量,但还没有尝试过全局变量。 - igagismutable
,g++就能够接受这段代码。很奇怪。 - chia
,那么这个错误(或者应该是警告?)是有效的,因为全局变量不需要被捕获,它们可以在lambda内部直接访问。 - igagisg++
通过引用捕获了a
。 - igagis