I am trying to make template wrapper function, that should forward parameters and return value. And I can't decide what is better to use auto&& or decltype(auto) for return type. I've read Scott Meyers article and understood that it is necessary to return decltype(auto) compared to auto not to strip ref_qualifiers.
As far as I understand the same argument works for using auto&& over auto.
Now I have following questions:
decltype(auto) and auto&& when we return reference to object?rvalue object, like: return int{};? Will return value be dangling reference?decltype(auto) and auto&&? What better fits as forward return type?'auto' lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression.
In C++14, you can just use auto as a return type.
What is the difference between
decltype(auto)andauto&&?
decltype(auto) covers three cases. When returning lvalues, the return type would be T& (lvalue-reference); for xvalues, the return type would be T&& (rvalue-reference); for prvalues, the return type would be T (non-reference, i.e. return by-value).
auto&& covers only two cases. When returning lvalues, the return type would be T& (lvalue-reference); for rvalues, including xvalues and prvalues, the return type would be T&& (rvalue-reference). (Forwarding reference is always a reference.)
What happens if we return rvalue object, like:
return int{};? Will return value be dangling reference?
For auto&& the return type is rvalue-reference, so yes, the returned reference is always dangling. For decltype(auto) the return type is non-reference then no such trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With