问题描述
我很好奇传递默认参数不一致背后的故事是什么:
struct Example {
void run() {
int localVar = 0;
auto l = [=](){
// localVar = 100; Not allowed (const copy of localVar)
memberVar = 100; // allowed (const copy of this pointer - NOT const *this copy)
};
l();
}
int memberVar = 1;
};
为什么不通过 const 值(包括 const *this)将所有参数传递给 lambda 捕获?
这是理想的设计选择,还是实现限制的结果?
编辑:
我知道指向对象的 const 指针作为参数传递,对象本身可以修改,但指针本身不能。但这是读者必须知道的实现细节,乍一看并不明显。与我的主观观点一致,将通过常量值捕获 *this...
解决方法
为什么局部变量和成员变量的默认捕获不一致?
因为默认捕获根本不会捕获成员变量。捕获的是 this
指针。这就是“const”:您不能修改 this
。但是在非常量成员函数中,它是一个指向非常量的指针,因此您可以修改非常量成员。
你说得对,这是一种蹩脚的行为。
这就是为什么在 C++20 中,当默认捕获为 this
时,=
的隐式捕获(即通过引用)被弃用。
大概的意图是有一天将 =
更改为捕获 *this
(即按值)。