mercredi 2 décembre 2015

Does local reference to int provide any benefit?

Consider following two code samples:

void int_fun(int val) {}

void another_fun() {
    vector<int> test(1, 1);
    int& int_ref = test[0];
    int_fun(int_ref);
}

versus

void int_fun(int val) {}

void another_fun() {
    vector<int> test(1, 1);
    int int_val = test[0];
    int_fun(int_val);
}

Is it true that compiler can implement int_ref as no op, while in second case it will have to create a copy of test[0]? Or copy can be optimized out in second case too, and these two samples are equivalent in performance?

Example and question is motivated by the fact that sometimes for code clarity it is beneficial to create local object that would be right away passed to some function like in example.

Does using reference for primitive types (such as int, bool, etc) provide any benefit in such case, or reference and value are equivalent (or perhaps value is even better)?

Aucun commentaire:

Enregistrer un commentaire