Reputation: 191
Say I have a vector of objects
std::vector<int> data;
This vector will be very large (megabytes in size). I have a function that needs to return this data structure. If I return this data structure "by-value" will a copy of the vector be made?
std::vector<int> generate()
{
std::vector<int> data;
//Populate data
return data;
}
How efficient would this operation be compared to allocating the vector on the heap and passing a pointer to the vector?
std::vector<int>* generate()
{
std::vector<int>* data = new std::vector<int>();
//Populate data
return data;
}
Upvotes: 1
Views: 355
Reputation: 49976
In your particular case, most compilers will perform NRVO - Named Return Value Optimization. This means no data will be copied, but it is not guaranteed. There are cases when NRVO will not be used. In C++11 and up vector might still use move semantics which will be very efficent.
[edit]
To clarify, if you use C++11 compatible compiler then your code is efficient, if you are stuck with C++03 then to be safe better return in function parameter (by reference), as in some contexts you might end with copying.
Upvotes: 5
Reputation: 10048
Modern compilers know how to optimize this into a simple move. Your first example is sufficiently efficient; you don't need to do anything else.
Upvotes: 5
Reputation: 20080
If you use c++11 vector could be moved and it is very cheap, just few words exchanged
Upvotes: 0
Reputation: 3355
You could pass an empty std::vector
initially and then return by reference as follows if your code structure permits:
std::vector<int>& generate(std::vector<int>& _vec) {
// populate _vec
return _vec;
}
This saves from having to use pointers or create copies.
Upvotes: 0