How can I make the storage of C++ lambda objects more efficient?

后端 未结 5 1089
猫巷女王i
猫巷女王i 2021-02-05 07:16

I\'ve been thinking about storing C++ lambda\'s lately. The standard advice you see on the Internet is to store the lambda in a std::function object. However, none of this adv

5条回答
  •  感动是毒
    2021-02-05 07:25

    Using C++14, you can avoid the copies altogether:

    int main()
    {
        Simple test( 5 );
    
        std::function f =
        [test = std::move(test)] ()
        {
            return test.Get();
        };
    
        printf( "%d\n", f() );
    }
    

    To produce the output:

    Constructing simple!
    Moving simple!
    Moving simple!
    Destroying simple!
    5
    Destroying simple!
    Destroying simple!
    

    Note the following line:

    [test = std::move(test)] 
    

    Here, the first appearance of "test" is in a different scope than the second.

提交回复
热议问题