【发布时间】:2021-07-10 07:33:04
【问题描述】:
我很好奇以下与传递默认参数不一致的原因:
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 指针作为参数传递,对象本身可以修改,但指针本身不能。但这是读者必须知道的实现细节,乍一看并不明显。从我的主观角度来看,将通过 const 值捕获 *this...
【问题讨论】:
-
const-ness 不可传递。this是 const,*this不是 const。