c++smart-pointersrange-based-loop

Iterating over a vector of shared_ptrs in a range-based for loop


I feel like this should have an answer already but I wasn't able to find it.

I have a vector of shared_ptrs:

vector<shared_ptr<X>> v;

I don't want to do anything with ownership (e.g. copying smart_ptrs) and I just want to go over the elements. Is there any reason why I shouldn't use references (performance or otherwise, e.g. could using references prevent some compiler optimzations or can using references make me run into any trouble)?

for (auto const& x : v)

vs:

for (auto x : v)

Solution

  • Just so this question doesn't stay unanswered I'm answering it myself.

    So it looks like there's no reason not to use references (no pitfalls or performance-related issues). Const references, to be specific.

    Also please read Andrej Podzimek's comment to my question.