I have a function copying one vector to another (among many other things). A simplified version of the code is below.
void Fun(std::vector<double> &in, std::vector<double> &out) {
out = in;
}
I care about maximizing efficiency because the function will be run many times. So, I would like to avoid reallocating memory as much as possible. The vector 'in' may already have a significant amount of memory reserved to it. So, if I made a manual implementation, I am sure that I could accomplish this. For example:
void Fun(std::vector<double> &in, std::vector<double> &out) {
out.resize(in.size());//note - if the capacity of out is greater than in.size(), this will involve no memory release or allocation
for (unsigned int i = 0;i<in.size();i++) {
out[i] = in[i];
}
}
If in.size() is less than the existing capacity of out, then this latter implementation will not release or assign any new heap memory.
The question is - would my original implementation do the same? Ie, would std::vector know to automatically do this in a memory efficient way if I simply did "out = in;"?
In particular, I am concerned that perhaps the "out = in;" line might do something like release all the heap memory currently allocated to out, and then reallocate it. Something effectively equivalent to this:
void Fun(std::vector<double> &in, std::vector<double> &out) {
out.clear();
out.shrink_to_fit();//releasing memory from heap
out.resize(in.size());//reallocating memory from heap
for (unsigned int i = 0;i<in.size();i++) {
out[i] = in[i];
}
}