问题描述
请考虑以下代码段:
#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;
}
我希望得到相同的结果:in f
, v
通过const引用传递,因此 v [i]
应该具有 const int&
类型。
I was expecting the same result: in f
, v
is passed by const reference, so v[i]
should have const int&
type.
但是,我得到结果
0 3
如果我不使用std :: function ,一切都很好:
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;
}
输出:
3 3
因此我想知道:
-
在第二个片段中,lambda表达式的返回类型是什么?
f
?f
与g
相同吗?
在第一个片段中,当构建 std :: function f
时发生了什么,导致错误?
In the first snippet, what happened when the std::function f
was constructed, causing the error?
推荐答案
lambda的返回类型使用 auto
返回类型推导规则,它剥离引用。 (最初它使用了一组稍微不同的基于左值到右值转换的规则(它也删除了引用),但是改变了。)
The return type of a lambda uses the auto
return type deduction rules, which strips the referenceness. (Originally it used a slightly different set of rules based on lvalue-to-rvalue conversion (which also removed the reference), but that was changed by a DR.)
因此, [& v] int i){return v [i];};
返回 int
。因此,在 std :: function< const int&(int)> f = [& v](int i){return v [i];};
,调用 f()
返回一个悬挂引用。绑定临时的引用会延长临时的生命周期,但在这种情况下,绑定发生在 std :: function
的机制中,所以到时间<$ c
Hence, [&v](int i) { return v[i];};
returns int
. As a result, in std::function<const int&(int)> f = [&v](int i) { return v[i];};
, calling f()
returns a dangling reference. Binding a reference to a temporary extends the lifetime of the temporary, but in this case the binding happened deep inside std::function
's machinery, so by the time f()
returns, the temporary is gone already.
g(3)
g(3)
is fine because the const int &
returned is bound directly to the vector element v[i]
, so the reference is never dangling.
这篇关于如果返回一个向量项,那么lambda表达式的返回类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!