For (auto & pointer: vectorOfPointers) vs for (auto pointer: vectorOfPointers)

I was wondering ... is there any real difference between :

for(auto &pointer : vectorOfPointers){pointer->fun();}

      

and

for(auto pointer : vectorOfPointers){pointer->fun();}

      

where is vectorOfPointers

declared to be simple vector

old school normal pointers:

std::vector<SomeType *> vectorOfPointers;

      

I know that &

in for(auto &o : objects)

stands for reference and that for(auto o : objects)

is a value loop. But the "values" in my examples are pointers themselves - I can access the objects they point to and modify them with both loops.

So is there a difference? If "not quite" (both in use and in what the compiler will generate from them), perhaps one of these two options is used / approved?

Not adding smart pointers to this discussion, I'm more interested in this exact situation.

+3


source to share


2 answers


So is there a difference?

In this particular example, no; both loops do the same thing and should produce (more or less) the same code.

More generally, a non-const reference allows you to modify vector elements. Copy doesn't work, but (for complex types) can be less efficient and requires the type to be copied.



Perhaps one of these two options is commonly used / approved?

I use the same rule of thumb as for function parameters: by referencing non-const only if I want to allow modification; otherwise, by value for simple types, or by const reference for complex or non-copyable types.

+4


source


In the first case, you have references to pointers in your vector. In the second case, you have copies of pointers from your vector. If you want to change pointer

, only in the first case the pointers inside your vector will also be changed.



The fact that your vector contains pointers is really besides point. This behavior does not change.

+1


source







All Articles