【问题标题】:Why default capture is not consistently const for both local variables and member variables?为什么局部变量和成员变量的默认捕获不一致?
【发布时间】: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。

标签: c++ c++11 c++17


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    这就是为什么在 C++20 中,当默认捕获为 = 时,不推荐隐式捕获 this(即通过引用)。

    大概的意图是改变= 以捕获*this(即按值)。

    【讨论】:

    • 我假设/希望意图是改变= 以完全不捕获thisthis 只能通过明确列出来捕获。如果需要捕获*this 的值,则捕获auto copy = *this。但这只是我的看法。
    • @eerorika 如果这是本意,& 捕获 this 也将被弃用。
    • 我不认为this& 捕获是一个大问题,因为这样可以减少混淆的空间。但仅仅因为this= 捕获会令人困惑,并不意味着*this= 捕获也不会令人困惑。
    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2012-04-28
    • 2015-10-21
    相关资源
    最近更新 更多