C + + lambda

Source: Internet
Author: User

The simplest lambda:

int Main () {    = []{};    Lambda ();}

To make lambda more useful, you need to capture local variables.

#include <stdio.h>int  main () {    int1;         = [x] {         printf ("x=%d", x);     };     Lambda ();}

[x] is a value-based snap, and the one that the lambda corresponds to is a const. This equivalent can be mended by the brain:

#include <stdio.h>intMain () {intx=1; classunnamed_functor{ Public: Unnamed_functor (intarg): x{arg}{}void operator()()Const{
x=2; Error, the member variable cannot be modified within the Const function printf ("x=%d", x); } intx; }; Unnamed_functor lambda{x}; Lambda ();}

You can use mutable to re-mark the lambda function, which clears the const tag. For example:

#include <stdio.h>int  main () {    int1;         = [x] mutable{         x=2;        printf ("inLambda x=%d\n", x);     };     Lambda ();    printf ("x=%d\n", x);}

[&y] is to catch local variables by reference. For example:

#include <stdio.h>int  main () {    int2;         = [x, &y] {         y=3;        printf ("inLambda y=%d\n", y);     };     Lambda ();    printf ("y=%d\n", y);}

As you can see, local variables captured by reference are also able to change the Y value without marking mutable. The brain complements the following pseudo-code:

#include <stdio.h>intMain () {intx=1, y=2 ; classunnamed_functor{ Public: Unnamed_functor (intV_bint&y_): X{x_},y (y_) {}void operator()()Const{            //x=2 Error, member variable cannot be modified within const functiony=3; printf ("In Lambda y=%d\n", y); }        intx; int&y;         };    Unnamed_functor Lambda (x, y);    Lambda (); printf ("y=%d\n", y); }

Here's an amazing knowledge blind spot where the const member function modifies the reference data member. A careful analysis of the const member function, the key intention is not to change the state of the object. For int& y data members, you cannot change the object that this reference points to.
When checking for y=3, it does not change the object that Y points to (the nature of the reference is a pointer or object address) and therefore does not contradict the const. This explains that Lambda does not have to add mutable to solve the problem of modifying local variables that reference snaps.

As a callable, lambda can accept arbitrary invocation parameters:

int Main () {    int x=1;     = [x] (intreturn x+arg;}     << Lambda (2//  show 3}

C++14 start, Lambda can have its own internal state variables. In the past there were only two state sources: [] captured local variables (automatic storage duaration cannot be global variables) () snap call parameters.
For example:

#include <stdio.h>0] () mutable {  return x + +;}; int Main () {    //  = = 0    / = = 1    //  = = 2 }

The brain complements the equivalent of this thing:

#include <stdio.h>classgenerator{ Public: Generator (): X (0){}    int operator()(){        returnX + +; }    intx;};intMain () {Auto a= Generator ();//= = 0Auto B = Generator ();//= = 1Auto c = Generator ();//= = 2}

The lambda snapping capability is further enhanced to capture arbitrary expressions. Consider the following questions:

#include <stdio.h><memory>int  main () {    = std::make_unique<int > (1);     // Auto q = p; Error: Cannot copy     // Auto k = Std::move (p); OK: can move copy = [ p] {         //...              };}

Obviously, the method of passing the value failed because UNIQUE_PTR does not support copy. To do this, use the new syntax for c++14:

#include <stdio.h><memory>int  main () {    = std::make_unique<int > (1);     // Auto q = p; Error: Cannot copy     // Auto k = Std::move (p); OK: can move copy    Auto lambda = [k=std::move (p)] {         //...     };}

The lambda captures the syntax of this pointer:

#include <stdio.h>#include<memory>structMYOBJ {intvalue{123 }; MYOBJ ()=default; MYOBJ (Constmyobj&Other ) {Value=Other.value; printf ("MYOBJ (const myobj& Other) \ n"); } Auto Getvaluecopy () {return[* This] {returnvalue;}; } Auto Getvalueref () {return[ This] {value=111;returnvalue;}; }};intMain () {MyObj mo; Auto Valuecopy=mo.getvaluecopy (); Auto Valueref=Mo.getvalueref (); Mo.value=321; Valuecopy (); //123Valueref ();//321printf ("%d\n", Mo.value); }

Reference: Https://github.com/AnthonyCalandra/modern-cpp-features#lambda-capture-this-by-value

C + + lambda

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.