为什么使用通用引用来接受函数结果而不是 decltype(auto)?

问题描述 投票:0回答:1
auto && result = foo();

decltype(auto) result = foo();

唯一的区别是,当 foo 的返回类型不是引用时,前者的类型是右值引用,而后者的类型不是引用。

声明 返回整数 返回整数& 返回整数&&
汽车 int int int
自动&& int&& int& int&&
decltype(自动) int int& int&&
c++ c++20
1个回答
0
投票

考虑:

constexpr auto f() -> /* #1 */  {
    /* #2 */ r = g();
    return r;
}

如果

g
返回纯右值(假设
int
),则:

#1
#2
结果
auto&&
auto&&
悬挂参考
auto&&
decltype(auto)
悬挂参考
decltype(auto)
auto&&
悬挂参考
decltype(auto)
decltype(auto)
回归
int
© www.soinside.com 2019 - 2024. All rights reserved.