简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM