Often, a function constructs a complicated result, for example a vector
of objects. In plain, unoptimized C++, this can easily lead to many intermediate copies. I wonder how I should construct such an object in order to avoid unnecessary copies.
The following function shows what I'd like to do and how one could naively implement it. The calls on db
are just pseudocode to roughly show the structure of the function.
vector<Result> get_result(Query q){
vector<Result> ret;
db.start_query(q);
while(db.has_more()){
int i = db.get_next_int("i");
string s = db.get_next_str("s");
Result result(i, s);
ret.push_back(result); // copy on push
}
return ret; // copy on return
}
How should I implement that kind of function considering modern C++11 or newer, and move semantics? It's possible to change the signature of the function, so that the vector<Result>
could become an input parameter that catches the results.