0

When we need to use " &" and when not to?
for example in below, both for loops produce identical result.

std::vector< Product* > itemByColor = pF.by_color( vecProds, Color::Red );

for( auto i : itemByColor )
{
     std::cout << " product name <<" << i->name<< std::endl;
}

AND

for( auto& i : itemByColor )
{
     std::cout << " product name <<" << i->name<< std::endl;
}
samprat
  • 2,150
  • 8
  • 39
  • 73
  • as long as you only *read* the value, there should not be much difference between a copy and a reference – sp2danny Feb 04 '17 at 12:09
  • @sp2danny: For smallish objects, such as `int`s, taking a reference can actually degrade performance. – 3442 Feb 04 '17 at 12:10

1 Answers1

1

More or less the same as whether you would decide to type std::string or (const) std::string&. That is, whether you want to copy the object or to take a reference to it.

std::vector<int> my_vector{ 1, 2, 3, 4, 5 };

int copy = my_vector[ 0 ];
int& reference = my_vector[ 0 ];

++copy;
std::cerr << my_vector[ 0 ] << '\n'; // Outputs '1', since the copy was incremented, not the original object itself

++reference;
std::cerr << my_vector[ 0 ] << '\n'; // Outputs '2', since a reference to the original object was incremented

// For each 'n' in 'my_vector', taken as a copy
for( auto n : my_vector )
{
    // The copy ('n') is modified, but the original remains unaffected
    n = 123;
}

// For each 'n' in 'my_vector', taken as a reference
for( auto& n : my_vector )
{
    // The original is incremented by 42, since 'n' is a reference to it
    n += 42;
}

// At this point, 'my_vector' contains '{ 44, 44, 45, 46, 47 }'
3442
  • 8,248
  • 2
  • 19
  • 41