以执行函数的返回类型的通用处理

以执行函数的返回类型的通用处理

本文介绍了decltype(auto)vs auto&&以执行函数的返回类型的通用处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

使用自动&&处理一个函数返回一个左值:

When using auto&& to handle a function returning a lvalue:

int func()
{
   int v=42;
   return v;
}

auto && v = func();

将v作为引用而不是lvalue的后果是什么?这些结果证明使用decltype(auto)而不是auto&&以执行函数的返回类型的通用处理?

What is the consequences that v be treated as a reference instead of a lvalue? Is these consequences justify the use of decltype(auto) instead of auto&& to perform generic handling of function's return type ?

推荐答案

auto&&< / code >已经是捕获函数返回值的最佳值,因此 decltype(auto)的差异只能是缺点。在您的示例中,生命周期扩展应用于从函数返回的其他临时对象。这导致它的行为与直接命名的对象基本相同,其效果是引用限定符擦除。

auto&& is already optimal for capturing function return values, such that the differences of decltype(auto) can only be disadvantages. In your example, lifetime extension is applied to the otherwise-temporary object returned from the function. This causes it to behave essentially the same as a directly named object, with the effect that the reference qualifier gets "erased."

使用 decltype auto)使用返回值函数导致其返回值对象被移动到本地。根据函数内部的内容,复制elision可以应用,其消除了本地和临时之间的区别。但是这只适用于有时,而引用绑定的生命期扩展是无条件的。

Using decltype(auto) with a return-by-value function causes its return value object to be moved into the local. Depending what's inside the function, copy elision may apply which removes the distinction between the local and the temporary. But that only applied sometimes, whereas reference-bound lifetime extension is unconditional.

即使应用,复制elision也不会移除要求返回对象被复制或移动。 decltype(auto)不能从函数返回初始化不可移动类型的对象,而 auto&&< / code >可以用一个局部的生命周期来模拟局部和临时之间的区别。

Even when applied, copy elision doesn't remove the requirement that the return object could be copied or moved. decltype(auto) can't initialize an object of non-movable type from a function return whereas auto && can, modulo the distinction between a local and a temporary with the lifetime of a local.

在这种情况下,只能通过 decltype ,并且只能通过 decltype(auto)在本地作用域之外创建。由于您通常希望将生命期延长的对象视为本地化对象,因此最好在使用<$ c时考虑圆括号和 std :: decay $ c> decltype ,而不是对函数参数使用 decltype(auto)(这是 auto&&& )。

As it happens, that distinction can only be made by decltype, and it can only be made outside the local scope by decltype(auto). Since you usually want to treat lifetime-extended objects as locals, it is best to mind parentheses and std::decays when using decltype, and not to use decltype(auto) for function parameters (which is the most common application of auto &&).

这篇关于decltype(auto)vs auto&amp;&amp;以执行函数的返回类型的通用处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:14