Reputation: 5617
I have these functions:
vector<int> foo1() {
vector<int> v;
return v;
}
void foo2( vector<int>& parameter ) {
// Do something
}
void foo3( vector<int> par ) {
foo2( par );
}
...
foo2(foo1()); // Doesn't work (1)
foo3(foo1()); // Works (2)
Is there a way to keep function foo2 as it is, as it is the optimal way to pass vectors as parameters, and maybe overload it to make (1) work? Or is there a better way to do this?
Upvotes: 0
Views: 242
Reputation: 88225
Passing by reference is typically use for 'out parameters', parameters used to return a value to the caller:
void bar(int &i, int &j);
int i, j;
bar(i, j); // sets i and j
// use i and j values here
C++ happens to disallow binding temporaries to non-const lvalues. So this does not work:
bar(1,2);
However, there is a need to allow passing temporaries without copying them, and prior to C++11 this need was filled by allowing temporaries to bind to const lvalue references. This is a special rule which still prevents mistakenly using a temporary as an out parameter, but allows copying to be avoided.
Since you're using the vector as an input parameter and not an output parameter, that would be the appropriate way to avoid copying:
void foo2(vector<int> const ¶meter) {
// Do something
}
If the 'Do something' code does eventually make a copy of the vector then you'd be better off doing this:
void foo2(vector<int> parameter) {
// Do something
}
Because this allows the compiler to optimize the copying for you in specific cases of calling foo2
, perhaps eliminating the copy.
Upvotes: 2