-2

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) 
14
  • 6
    copying smart pointers is about ownership. You say you dont want to do anything about ownership, so why use anything else than const auto& ? Commented Aug 7, 2023 at 10:39
  • Go from the most restrictive one to the least - Does const auto& work for you? Use it. If it does not, then what is wrong? Commented Aug 7, 2023 at 10:39
  • @463035818_is_not_an_ai That's the gist of my question - using a reference seems like a good optimization but C++ is tricky so maybe I don't know about some important reason against it. Commented Aug 7, 2023 at 10:40
  • the answer is not different to iterating other element types. Use const auto& unless you need a copy or modification. Commented Aug 7, 2023 at 10:40
  • 2
    Copying a shared_ptr is 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 a shared_ptr in the for-loop is a perfectly reasonable performance optimization. The vector<shared_ptr<...>> keeps all shared_ptr pointees alive, so there’s no lifespan concern within the loop. But do copy the shared_ptr when giving out co-ownership outside the loop’s scope. Commented Aug 7, 2023 at 12:30

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.