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
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.