请考虑以下代码段:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我期待相同的结果:in f,v由const引用传递,所以v[i]应该有const int&类型.
但是,我得到了结果
0 3
Run Code Online (Sandbox Code Playgroud)
如果我不使用std :: function,一切都很好:
#include <iostream>
#include <vector>
#include <functional>
int main()
{
std::vector<int>v = {0,1,2,3,4,5,6};
auto f = [&v](int i) …Run Code Online (Sandbox Code Playgroud)