为什么默认捕获对于局部变量和成员变量不一致?

Why default capture is not consistently const for both local variables and member variables?

我很好奇传递默认参数不一致背后的故事是什么:

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 指针作为参数传递,对象本身可以修改,但指针本身不能。但这是 reader 必须知道的实现细节,乍一看并不明显。从我的主观角度来看,一致的是通过 const 值捕获 *this...

Why default capture is not consistently const for both local variables and member variables?

因为默认捕获根本不捕获成员变量。捕获的是this指针。那就是“const”:您不能修改 this。但在非常量成员函数中,它是指向非常量的指针,因此您可以修改非常量成员。

你是对的,这是一个蹩脚的行为。

这就是为什么在 C++20 中当捕获默认值是 =.

时不推荐使用 this 的隐式捕获(即通过引用)

大概的目的是改变=一天捕获*this(即按值)。