Purpose std :: function <int (int)> to std :: function <const int & (const int & x)>

The following code compiles, but outputs undefined output in VC ++ 2015 (release) and a runtime error using other compilers .

#include <functional> #include <iostream> int main() { std::function<int(int)> f = [](int x) { return x; }; std::function<const int&(const int& x)> g = f; std::cout << g( 42 ) << std::endl; } 

Why is the purpose of g = f; ?

+5
source share
2 answers

Consider the equivalent code rewritten to avoid lambdas or std::function :

 int f(int x) { return x; } int const& g(int const& x) { return f(x); } 

This is a perfectly well-formed code, which nevertheless returns a broken link to a temporary one and, thus, leads to undefined behavior. The source code is provided for the same reason: you can implicitly convert the object to a link of the same type. Unfortunately, in this case.

+5
source

The value of r can be bound to a const& . A const& can be converted to r.

Learn this:

 int f(int x){return x;} int const& g(int const& x){ return f(x); } 

Similarly, calling g is legal, there are no errors, but reading the result g(42) - UB - the link is cheating.

A good compiler will see a link related to a temporary return and warning.

function simply checks if types can be converted; he does not analyze all his life. Perhaps this should be because we can detect this error statically.

+4
source

Source: https://habr.com/ru/post/1246246/


All Articles