隐式捕获“*this”的引用。那是什么,与隐式捕获“这个”的副值有什么区别?

Implicit capture of "*this" by-reference. What's that and what's the difference to implicit capture of "this" by-value?

提问人:Johannes Schaub - litb 提问时间:4/24/2023 更新时间:4/24/2023 访问量:126

问:

Cppreference 在 https://en.cppreference.com/w/cpp/language/lambda (

如果存在任一捕获默认值,则可以隐式捕获当前对象 (*this)。如果隐式捕获,则始终通过引用捕获它,即使捕获默认值为 =。

我试图理解所有这些文字,但失败了。

  1. “隐式捕获按引用”与“隐式捕获按值”有什么区别?*thisthis
  2. 为什么你不能通过引用显式捕获它,即通过?&*this
C++ lambda c++17 这个

评论


答:

4赞 HolyBlackCat 4/24/2023 #1

“隐式捕获*此副引用”与“隐式捕获此副值”有什么区别?

没有。这是说同一件事的两种方式。

为什么你不能通过引用显式捕获它,即通过?&*this

你可以,但它是拼写的.this


cppreference 和一些人之所以使用看似迂回的措辞“通过引用捕获 *this”而不是“通过值捕获,是因为这简化了 的措辞,现在可以说是默认通过引用捕获所有内容,包括 .[&]*this

这种措辞也使它看起来像一个例外(它通过引用捕获,但其他所有内容都通过值捕获),这是有道理的,因为它捕获(以任何方式)已被弃用。[=]*thisthis

0赞 joergbrech 4/24/2023 #2

文本说,如果您使用 capture-default 或 .我相信这是为了方便起见,这样你就可以很容易地编写可以访问当前对象成员的lambda:*this=&


struct Foo {

    void baz() {
        [=]{ // or use [&], the captures have the same effect
            bar = 42;
        }();
    }

    int bar {5};
};

这将改变,因为在 C++20 中不推荐使用 capture-default 的隐式捕获。*this=

https://godbolt.org/z/ff8ePehbW

为什么不能通过引用显式捕获它

您始终可以按值显式捕获指针!它看起来像这样:this

struct Foo {

    void baz() {
        [this]{
            bar = 42;
        }();
    }

    int bar {5};
};