I started investigating the answer to your question thinking I understand references. It turned out they are more complicated than I thought.
I wanted to say that, looking at your code, it depends what you want to do with the
item_r
and
item_rr
. Being a rvalue reference, I would have expected that you cannot say something like:
template <class T>
T do_something_rval (std::vector<T>& container) {
T t = 0;
for (auto&& item_rr : container) {
t += item_rr;
item_rr = t; }
return t;
}
However I didn't get any error neither on definition nor on instantiation (my compiler is MSVC++ 19 updated with latest patches):
int main ()
{
vector<int> v1 = { 1, 2, 3, 4, 5 };
int sum_rval = do_something_rval (v1);
cout << "v1";
for (auto i : v1)
cout << " " << i;
cout << " sum=" << sum_rval << endl;
And the output:
v1 1 3 6 10 15 sum=15
shows that you can modify an object through a rvalue reference.
If, however, I change the 'auto' to an explicit type:
template <class T>
T do_something_rval (std::vector<T>& container) {
T t = 0;
for (int&& item_rr : container) {
t += item_rr;
item_rr = t;
}
return t;
}
I get an error:
Error C2440 'initializing': cannot convert from 'int' to 'int &&'
It goes to show that for auto declarations the compiler drops any rvalue reference specifications.
My conclusion: there is no point in using rvalue reference for auto declarations.