Decltype (auto) vs auto && to do general handling of the return type of a function

When using auto&& to handle a function that returns an lvalue:

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

What are the consequences of handling v as a link rather than an lvalue? decltype(auto) Do these consequences use decltype(auto) instead of auto&& to perform general processing of the return type of the function?

+4
c ++ c ++ 14
Nov 20 '13 at 7:15
source share
1 answer

auto&& already optimal for capturing the return values ​​of a function, so decltype(auto) differences can only be disadvantages. In your example, the life extension is applied to the temporary object returned by the function. This leads to the fact that it behaves essentially the same way as a directly named object, so that the reference qualifier gets "erased".

Using decltype(auto) with the return-by-value function moves the return value object to local. Depending on what is inside the function, a copy may be used that eliminates the distinction between local and temporary. But this only applies sometimes, while the binding of binding to binding to a link is unconditional.

Even when applied, copy elision does not eliminate the requirement that the returned object can be copied or moved. decltype(auto) cannot initialize an object of an immovable type from the return function, whereas auto && can, modulo the difference between local and temporary with the local lifetime.

As it happens, this distinction can only be made by decltype , and it can only be made outside the local scope of decltype(auto) . Since you usually want to treat objects extended for life as local, it is best to avoid parentheses and std::decay when using decltype , rather than using decltype(auto) for function parameters (which is the most common auto && application).

+5
Nov 20 '13 at 10:08
source share



All Articles