Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based for loop with decltype(auto)

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) {
    // ...
}
like image 963
s3rvac Avatar asked Jul 17 '16 12:07

s3rvac


Video Answer


1 Answers

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.

like image 185
Yakk - Adam Nevraumont Avatar answered Nov 01 '22 23:11

Yakk - Adam Nevraumont