Possible Duplicate:
how to “return an object” in C++
I am wondering if there is a difference between the three following approaches:
void FillVector_1(vector<int>& v) {
v.push_back(1); // lots of push_backs!
}
vector<int> FillVector_2() {
vector<int> v;
v.push_back(1); // lots of push_backs!
return v;
}
vector<int> FillVector_3() {
int tab[SZ] = { 1, 2, 3, /*...*/ };
return vector<int>(tab, tab + SZ);
}
The biggest difference is that the first way appends to existing contents, whereas the other two fill an empty vector. 🙂
I think the keyword you are looking for is return value optimization, which should be rather common (with G++ you’ll have to turn it off specifically to prevent it from being applied). That is, if the usage is like:
then there might quite easily be no copies made (and the function is just easier to use).
If you are working with an existing vector
then using an out parameter would avoid creation of vectors in a loop and copying data around.