Reputation: 20255
Is it safe returning a lambda like this:
auto doIt(const Object& obj) {
return [&obj]{ obj.doIt();};
}
It returns a lambda using local capture, but the reference is one that is passed into the function and not from a local variable.
Upvotes: 2
Views: 80
Reputation: 21576
auto doIt(const Object& obj) {
return [&obj]{ obj.doIt();};
}
That's probably not a good idea for the mere fact that doIt(const Object& obj)
can bind a temporary object. Imagine doing:
auto lm = doIt(make_object());
lm(); //Undefined behavior
That's because the temporary returned my make_object would be destroyed at the end of the function doIt
, but your returned lambda still holds a reference to the destroyed object.
Another example will be:
auto func(){
Object obj = make_object();
auto lm = doIt(obj);
lm(); //This is Ok
return lm;
}
void something{
auto val = func();
val(); //Undefined Behavior
}
EDIT: See the comments.
You can add a void doIt(const Object&&) = delete;
overload to prevent temporaries; Courtesy of @StoryTeller.
Upvotes: 4