In C++ 11, if I have a function that returns a std::vector<int>
with a very large number of elements, does this return a deep or shallow copy of the vector which was originally created?
E.g.
std::vector<int> GetVec()
{
std::vector<int> bar(1000000);
// Fill in bar with numbers
return bar;
};
int main()
{
std::vector<int> foo = GetVec();
return 0;
}
Will foo
be a deep copy of the entire contents of bar
, or will it just be a reference to bar
?
My understanding is the C++ functions return copies, so in this case, how should I avoid having the make a costly copy of bar
inside this function? I know that the elements of a std::vector
are created on the heap, so I'm wondering if copying bar
in the function creates a deep or shallow copy.
One way would be to pass foo
as an argument:
void GetVec(std::vector<int>& bar)
{
bar.resize(1000000);
// Fill in bar with numbers
};
Another way would be to return by reference:
std::vector<int>& GetVec()
{
std::vector<int> bar(1000000);
// Fill in bar with numbers
return bar;
};
But what's the best practice?