decltype(auto) vs auto&& to perform generic handling of function's return type

烈酒焚心 提交于 2019-12-04 23:40:01

问题


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

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

auto && v = func();

What are the consequences of treating v as a reference instead of an lvalue? Do these consequences justify the use of decltype(auto) instead of auto&& to perform generic handling of function's return type?


回答1:


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."

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.

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.

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 &&).



来源:https://stackoverflow.com/questions/20089682/decltypeauto-vs-auto-to-perform-generic-handling-of-functions-return-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!