The compiler creates an anonymous function object upon evaluating a lambda expression.
This function object, created by a lambda expression, may live longer than the block in which it is created. You must ensure that it does not use variables that were destroyed before the function object is used.
The following example shows how a function object created by a lambda expression can outlive the function that creates it.
struct Base {
virtual bool test(int x) = 0;
};
template<typename F>
struct Derived: Base {
F f;
bool test(int x) {return f(x);}
Derived(F f_) : f(f_) {}
};
template<typename F>
Base* MakeDerived( F f ) {
return new Derived<F>(f);
}
Base* Foo( int k ) {
return MakeDerived( [k](int x) {return x%k==3;} );
}
bool Bar() {
Base* b = Foo(3);
return b->test(6);
}
In the above example, Bar invokes Foo, which copies the function object generated by a lambda expression into an instance of template class Derived. The lambda expression refers to a local variable k. Although the code destroys k before using the copied function object, the code is safe because k was captured by copy.
Copyright © 1996-2010, Intel Corporation. All rights reserved.