// a normal way
vector<int> retVec()
{
vector<int> tmp { 1, 3, 5 };
return tmp;
}
If you start empty and do push_back, then you most likely invoke reallocations within the vector (unless the compiler miraculously is able to optimize them away). You could avoid those with:
where are you going to get those values. What you most definitely do NOT want to do is:
1 2 3 4 5 6 7 8
vector<int> retVec()
{
vector<int> tmp;
tmp.push_back(1);
tmp.push_back(3);
tmp.push_back(5);
return {tmp[0], tmp[1], tmp[2] }; // Look how smart I am!
}
This is actually slower than
1 2 3 4 5 6 7 8 9
// a normal way
vector<int> retVec()
{
vector<int> tmp;
tmp.push_back(1);
tmp.push_back(3);
tmp.push_back(5);
return tmp;
}
This is because of "copy elision" (did I spell that right?). The compiler will recognize that tmp is the return vector and will store it in the return value. So when you return, it doesn't have to make a copy at all.
But this is like optimizing a ventilation system by examining how much air is moved by flies. It's a tiny gain and probably not worth any consideration.