Is there a situation when decltype(auto)
would be a better choice than auto
(possibly with &
, &&
, or cv qualifiers) when using range-based for loops? In other words, would you ever write the following code?
for (decltype(auto) item : range) {
// ...
}
decltype(auto)
generates a different type when the input iterator returns by value. auto&&
creates an rvalue reference to the temporary, while decltype(auto)
creates a local copy (in C++17 it just names the temporary because of the guaranteed elision change).
This has little difference. In C++11/14, it requires a move ctor (that is not called in practice, but required) in the decltype(auto)
case, but not in C++17. In the auto&&
the move ctor is not called and not required.
Another difference is the type of decltype(item)
, which is a reference always with auto&&
, but in the case of the temporary returning input iteraror decltype(item)
is a value type.
That is about it. In practice, I see no reason to decltype(auto)
over auto&&
.
As an aside, auto&
forces non-rvalue, const auto&
forces non-mutable, and auto
forces a copy. There are reasons to use auto&&
instead of those, but that is outside the scope of this question. decltype(auto)
is closest to auto&&
, so I compared those two.
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