Consider this:
#include <vector>
std::vector<int> f() {
std::vector<int> v{1, 2};
return v;
}
void test() {
auto v = f();
v = f(); <---- HERE
}
Will the compiler “reuse” the space assigned to v
in the call marked with HERE
or create a complete new vector?
Alternatively, consider:
#include <vector>
std::vector<int> f(std::vector<int>&& v = {}) {
// v might not be empty, so be careful!
v = {1, 2};
return v;
}
void test() {
auto v = f();
v = f(std::move(v));
}
In that approach, a) I don’t like that v
might not be empty, so one has to be careful in the function and b) v
is initialised with a default with is also not optimal.
What’s a good pattern to design f
in a way that it would potentially get a reusable vector?