Search code examples
c++lambdathisc++20capture

Why do lambda functions need to capture [this] pointer explicitly in c++20?


Pre-c++20, the this pointer is captured in [=] implicity. So what's the reason that c++20 decided that user should write [=, this] to capture this pointer explicitly, I mean, without this change, the pre-c++20 code could have any code-smell or potential bug?

Any good sample or reason for this language change?


Solution

  • This is explain in P0806, which as the title says, "Deprecate[d] implicit capture of this via [=]"

    The argument in the paper is that at this point we had [this] (captures the this pointer) and [*this] (captures the object itself), and [&] (captures the object by reference, which is basically capturing the this pointer by value). So it could be ambiguous whether [=] should mean [this] or [*this] and potentially surprising that it means the former (since [=] functions as a reference capture in this context).

    Thus, you have to write [=, this] or [=, *this], depending on which one of the two you actually intended.


    As an aside, it's worth nothing that the paper claims:

    The change does not break otherwise valid C++20 code

    Yet if you compile with warnings enabled and -Werror, as many people do (and should unless you have a compelling reason not to - which there are), this change of course broke lots of otherwise valid C++20 code.