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)
const auto&?const auto&work for you? Use it. If it does not, then what is wrong?const auto&unless you need a copy or modification.shared_ptris expensive, because it points at a shared thread-safe reference counter. The copy will (atomically) increment the counter. This atomic operation costs (depending on the architecture) a time equivalent of thousands of arithmetic instructions in local registers. Using references to ashared_ptrin thefor-loop is a perfectly reasonable performance optimization. Thevector<shared_ptr<...>>keeps allshared_ptrpointees alive, so there’s no lifespan concern within the loop. But do copy theshared_ptrwhen giving out co-ownership outside the loop’s scope.