Why can std :: function be built using lambda with a different return type?

The following compiles fine :

#include <functional> int main() { std::function<const int&()> f = []() -> int {return 1;}; const int& r = f(); // r is a dangling reference return 0; } 

How can I set std::function with return type const int& to lambda with return type int ? The resolution of this type of cast occurs implicitly and without warning - this is gotcha IMHO.

+9
c ++ lambda std-function
Jan 09 '17 at 13:56 on
source share
1 answer

You can build std::function with any object called with the appropriate arguments, and whose return value is implicitly converted to return std::function . int implicitly converted to const int& therefore rules are executed.

The compiler may be free to warn about this, but it seems like a lot of work for a particularly angular case.

+5
Jan 09 '17 at 14:05
source share



All Articles