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

1

8

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?

Bloomers answered 1/8, 2022 at 16:27 Comment(1)
I think you'll find the motivation in p0409r2Hawn
I
16

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.

Insensitive answered 1/8, 2022 at 16:42 Comment(3)
"this change of course broke lots of otherwise valid C++20 code." That's true of deprecating anything.Evaporimeter
Not necessarily lots. Deprecating comma within [] (another deprecation in C++20) probably affects way less existing code than this one. Still not zero, of course.Midsummer
@Midsummer For the code that I dealt with, it was absolutely lots. This deprecation was, by far, the biggest change we had to make in upgrading to C++20.Insensitive

© 2022 - 2024 — McMap. All rights reserved.