简体   繁体   中英

What is the difference between returning auto&& and decltype(auto)?

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:

  1. Am I right, that there is no difference between decltype(auto) and auto&& when we return reference to object?
  2. What happens if we return rvalue object, like: return int{}; ? Will return value be dangling reference?
  3. What is the difference between decltype(auto) and auto&& ? What better fits as forward return type?

What is the difference between decltype(auto) and auto&& ?

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM