vendredi 1 juillet 2016

Passing to a Reference Argument by Value


Consider this simple program:

vector<int> foo = {0, 42, 0, 42, 0, 42};
replace(begin(foo), end(foo), foo.front(), 13);

for(const auto& i : foo) cout << i << 't';

When I wrote it I expected to get:

13 42 13 42 13 42

But instead I got:

13 42 0 42 0 42

The problem of course is that replace takes in the last 2 parameters by reference. So if either of them happen to be in the range being operated on the results may be unexpected. I can solve this by adding a temporary variable:

vector<int> foo = {0, 42, 0, 42, 0, 42};
const auto temp = foo.front();
replace(begin(foo), end(foo), temp, 13);

for(const auto& i : foo) cout << i << 't';

I do know that C++11 gave us all kinds of type tools is it possible that I could simply force this value to a non-reference type and pass that inline, without creating the temporary?


Aucun commentaire:

Enregistrer un commentaire