mardi 13 avril 2021

returning by reference and copy the value

i was reading about r-value references in c++ and i saw this example. i tried to understand why the returning value in line 15 isn't a copy while the returning value in line 14 is but i couldn't.

1 LargeType randomItem1(const vector<LargeType> & arr)
2 {
3 return arr[randomInt(0, arr.size( ) - 1)];
4 }
6
5 const LargeType & randomItem2(const vector<LargeType> & arr)
7 {
8 return arr[randomInt(0, arr.size( ) - 1)];
9 }
10
11 vector<LargeType> vec;
12 ...
13 LargeType item1 = randomItem1(vec);  **// copy**
14 LargeType item2 = randomItem2(vec);  **// copy**
15 const LargeType & item3 = randomItem2(vec);  **// no copy**

Aucun commentaire:

Enregistrer un commentaire