This question already has an answer here:
- How to pass objects to functions in C++? 7 answers
I have years of experience in C but I am new to C++. I see everyone is recommending passing a reference to vectors instead of passing a pointer. I totally understand the syntax but actually I don't understand the rational of this advice. Since passing the container by reference or by value is dependent on the implementation of the function, the data change is the responsibility of the function called not the owner function. I believe that this makes understanding the code and its readability difficult! And probably passing or a pointer would probably have the same performance.
void foo_1(vector<int> bar);
void foo_2(vector<int> &bar);
void foo_3(vector<int> *bar);
int main(){
vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//I must check the implementation to know that foo_2 will be changing my data!
foo_1(v);
foo_2(v);
//Clearly I must take care when passing my data it is a pointer!
foo_3(&v);
}
Aucun commentaire:
Enregistrer un commentaire