How to use auto with const and & in C++?
Even though the two forms are equivalent in this case, I would choose the first form anyway, since it communicates better the fact that your piece of code does not need to modify the state of the object returned by someMethod()
.
So my advice is to go for this:
const auto &items = someObject.someMethod();
In your case, there is no difference. The type which auto
represents will be deduced to const A
in both cases, so the type of items
will be const A&
.
There is a difference in what the "self-documented semantics" of the code is. The const auto &
clearly states "I want a reference to what is returned, and I will not modify it." Just auto &
says simply "I want a reference to what is returned."