0

Assumed that we have defined a vector (regardless of size and type of the elements; but vec.size() >= 1) and we want to iterate through the entire vector, but do not want to modify any element:

std::vector<type> vec = someData;

for (type item : vec) {
   // do something
   // but assumed no manipulation of item
   // I can access item which is a copy of vec[i]
}

for (const type &item : vec) {
   // do something
   // but assumed no manipulation of item
   // I can access item which is a immutable reference to vec[i]
}

Both – copy and reference – will create new memory, either with a copy of the value or the address to that value in vec[i] (remind: we only want to look at the elements!).

For complex types in vec it is definitely more efficient to use a reference, because the size of the reference in the memory is less than the actual element in vec[i].

But what if the elements in vec are of type int with 4 Bytes width or so? Will the address or the actual int contain a bigger size? So rather use a copy or a reference?

(I do not consider to use a reference for types like int or double! … but I am interested, so please make your answers general.)

Thanks :-)

lsc
  • 375
  • 6
  • 15
  • 2
    ***Both – copy and reference – will create new memory, either with a copy of the value or the address to that value in vec[i] (remind: we only want to look at the elements!).*** A reference does not necessarily need any additional storage even for the address. – drescherjm Nov 27 '20 at 15:54
  • a reference is just an alias. It does not necessarily occupy any memory – 463035818_is_not_an_ai Nov 27 '20 at 15:58
  • Assume that additional memory is used for the address? Will the address be more in size or a simple int value, in average case? – lsc Nov 27 '20 at 15:58
  • Or in other words: a reference for the above example is more efficient? For int types too? Even if it does not make a huge difference? – lsc Nov 27 '20 at 15:59
  • 1
    any selfrespecting compiler will realize that no additional memory is needed for the reference in your code. Don't do premature optimization, look at the assembly – 463035818_is_not_an_ai Nov 27 '20 at 15:59
  • 1
    Even in the copy case, no additional memory might be needed. `item` might be just mapped to a register instead. – Daniel Langr Nov 27 '20 at 16:02
  • Okay! Thank you guys! – lsc Nov 27 '20 at 16:04
  • @lsc May be noteworthy, that the compiler can decide to use the same implementation as for a const reference of a const parameter value. – πάντα ῥεῖ Nov 27 '20 at 16:17

0 Answers0