What is generic lambda capture and why was it created?

I see a lot of questions in which generic lambda captures are used for different things, but nothing explains what they are and why they were added to the standard.

I read what the document seems to describe the updated standard needed for generalized lambda captures to exist , but it’s not. Actually, I say why they were created, and it really does not give a good summary of how they work. It's basically just a bunch of dry "strikes" here and add that language here. "

So what is this? Why do I want to use it? What rules do they follow? For example, it seems that it allows you to capture expressions. When are these expressions evaluated? If they lead to side effects, when do they take effect? If multiple expressions are evaluated, is there a guaranteed evaluation order?

+4
source share
1 answer

As usual, Scott Meyers offers a great explanation of what they are, why you would like to use them, and roughly what rules they follow in Effective Modern C ++ . Paragraph 32: Use the init capture to move objects to close. Here is a brief summary:

++ 11 - , . , , ++ 14 - , init.

  • , ,
  • , .

init - , .. ( ).

, init :

auto pw = std::make_unique<Widget>(); 

// configure *pw

auto func = [pWidget = std::move(pw)] { 
    return pWidget->isValidated() && pWidget->isArchived(); 
};

init ++ 11

  • :

    class IsValAndArch {
    public:
        using DataType = std::unique_ptr<Widget>;
    
        explicit IsValAndArch(DataType&& ptr) : pw(std::move(ptr)) {}  
        bool operator()() const { return pw->isValid() && pw->isArchived(); }    
    
    private:
        DataType pw;
    };
    
    auto pw = std::make_unique<Widget>();
    
    // configure *pw;
    
    auto func = IsValAndArch(pw);
    
  • std::bind:

    auto pw = std::make_unique<Widget>();
    
    // configure *pw;
    
    auto func = std::bind( [](const std::unique_ptr<Widget>& pWidget)
        { return pWidget->isValidated() && pWidget->isArchived(); },
        std::move(pw) );
    

    , lambda lvalue ( pw lvalue) const ( -, , ​​, const ).

init Anthony Calandra cheatsheet ++, , ( ).

+3

Source: https://habr.com/ru/post/1666070/


All Articles