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:
- Am I right, that there is no difference between
decltype(auto)andauto&&when we return reference to object? - What happens if we return
rvalueobject, like:return int{};? Will return value be dangling reference? - What is the difference between
decltype(auto)andauto&&? What better fits as forward return type?
decltype(auto)covers three cases. When returning lvalues, the return type would beT&(lvalue-reference); for xvalues, the return type would beT&&(rvalue-reference); for prvalues, the return type would beT(non-reference, i.e. return by-value).auto&&covers only two cases. When returning lvalues, the return type would beT&(lvalue-reference); for rvalues, including xvalues and prvalues, the return type would beT&&(rvalue-reference). (Forwarding reference is always a reference.)For
auto&&the return type is rvalue-reference, so yes, the returned reference is always dangling. Fordecltype(auto)the return type is non-reference then no such trouble.