PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

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

 November 04, 2022     c++, c++20, capture, lambda, this     No comments   

Issue

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.



Answered By - Barry
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing