Consider the following snippet:
#include <iostream>
#include <vector>
#include <functional>
int main()
{
std::vector<int>v = {0,1,2,3,4,5,6};
std::function<const int&(int)> f = [&v](int i) { return v[i];};
std::function<const int&(int)> g = [&v](int i) -> const int& { return v[i];};
std::cout << f(3) << ' ' << g(3) << std::endl;
return 0;
}
I was expecting the same result: in f
, v
is passed by const reference, so v[i]
should have const int&
type.
However, I get the result
0 3
If I do not use std::function, everything is fine:
#include <iostream>
#include <vector>
#include <functional>
int main()
{
std::vector<int>v = {0,1,2,3,4,5,6};
auto f = [&v](int i) { return v[i];};
auto g = [&v](int i) -> const int& { return v[i];};
std::cout << f(3) << ' ' << g(3) << std::endl;
return 0;
}
output:
3 3
Thus I'm wondering:
In the second snippet, what is the return type of the lambda expression f
? Is f
the same as g
?
In the first snippet, what happened when the std::function f
was constructed, causing the error?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…