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

后端 未结 5 1066
猫巷女王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:47

    Your first problem is simply that MSVC's implementation of std::function is inefficient. With g++ 4.5.1 I get:

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

    That's still creating an extra copy though. The problem is that your lambda is capturing test by value, which is why you have all the copies. Try:

    int main()
    {
        Simple test( 5 );
    
        std::function f =
            [&test] ()               // <-- Note added &
            {
                return test.Get();
            };
    
        printf( "%d\n", f() );
    }
    

    Again with g++, I now get:

    Constructing simple!
    5
    Destroying simple!
    

    Note that if you capture by reference then you have to ensure that test remains alive for the duration of f's lifetime, otherwise you'll be using a reference to a destroyed object, which provokes undefined behaviour. If f needs to outlive test then you have to use the pass by value version.

提交回复
热议问题