Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 vectorOfPointers is declared as simple vector of normal, old-school pointers:

std::vector<SomeType *> vectorOfPointers;

?

I know that & in for(auto &o : objects) stands for reference, while for(auto o : objects) is the loop on the values. But the "values" in my examples are pointers themselves - I can access the objects to which they point and modify them with both loops.

So, is there any difference? If "not really" (in both the usage and in what the compiler would generate from them), maybe one of those 2 options is an commonly used/approved one?

Lets not add smart pointers to that discussion, I'm rather interested in that precise situation.

like image 940
PolGraphic Avatar asked Dec 05 '25 09:12

PolGraphic


2 Answers

So, is there any difference?

In this specific 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 the vector elements. A copy doesn't, but (for complex types) might be less efficient, and requires the type to be copyable.

maybe one of those 2 options is an commonly used/approved one?

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

like image 200
Mike Seymour Avatar answered Dec 07 '25 23:12

Mike Seymour


In the first case you have references to the pointers in your vector. In the second case you have copies of the pointers from your vector. If you were to modify pointer, only in the first case would the pointers inside your vector also be modified.

The fact that your vector contains pointers is really besides the point. This behaviour is the same regardless.

like image 44
Joseph Mansfield Avatar answered Dec 08 '25 00:12

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!