2

What are the differences between for (auto&& i : v) and for (auto& i : v)?

I understand that auto&& is a universal reference. I clearly know auto && could return references of rvalues and lvalues. Does auto & only return a reference of lvalues. Am I right? Are there some potential problems with for (auto& i : v)?

Here is some related code:

#include <iostream>
#include <vector>
#include <typeinfo>

int main()
{
    std::vector<int> v = {0, 1, 2, 3, 4, 5};
    for (auto& i : v) 
    {
        std::cout << i << ' ';
        std::cout << typeid(i).name() << std::endl;
    }

    for (auto&& i : v) 
    {
        std::cout << i << ' ';
        std::cout << typeid(i).name() << std::endl;
    }
}
H.S.
  • 11,654
  • 2
  • 15
  • 32
John
  • 2,963
  • 11
  • 33
  • I do not think the suggested page answers this question.At least, for the question,"Does auto & only return a reference of lvalues?" – John Jun 10 '20 at 02:54
  • 1
    `auto&` cannot bind to rvalues. If the container's iterator returns rvalues rather than lvalues, the code will not compile. – Raymond Chen Jun 10 '20 at 03:09
  • @Raymond Chen How can I confirm which kind of reference it returns, e.g. vector, vector(their return types diff)? – John Jun 10 '20 at 03:14
  • You have to consult the documentation. For example, `vector`'s `reference` is a `T&`. Whereas `vector's is a separate class (a proxy). – Raymond Chen Jun 10 '20 at 03:56
  • @Raymond Chen What does "proxy" mean? Is it a terminology? – John Jun 10 '20 at 04:24
  • [Proxy pattern](https://en.wikipedia.org/wiki/Proxy_pattern). – Raymond Chen Jun 10 '20 at 04:29
  • @RaymondChen Quote:"vector's reference is a T&. Whereas `vector's is a separate class (a proxy). " If I correctly understand you, `vector` does not have any relationship with `vector`. Am I right? – John Jun 10 '20 at 04:40
  • [`vector` is a specialization of `vector`](https://timsong-cpp.github.io/cppwp/vector.bool). – Raymond Chen Jun 10 '20 at 15:28
  • @RaymondChen Thank you for the clarification. – John Jun 10 '20 at 15:39

0 Answers0