Unnecessary copying
Unnecessary copying of objects is probably C++ inefficiency #1. The main reason is that it’s easy to do and hard to notice. Consider the following code:
std::vector<int> v = make_v(… some args …); do_work(v);
How many copies of the vector v
are made in this program? The answer depends on the details of the functions make_v()
and do_work()
as well as the compiler optimizations. This tiny example covers several language subtleties that we will now discuss.
Copying and argument passing
We are going to start with the second function, do_work()
. What matters here is the declaration: if the function takes the argument by reference, const
or not, then no copies are made.
void do_work(std::vector<int>& vr) { … vr is a reference to v … }
If the function uses pass-by-value, then a copy must be made:
void do_work(std::vector<int> vc) { … vc is a copy of v … ...