I have a function which returns a vector or set:
set<int> foo() {
set<int> bar;
// create and massage bar
return bar;
}
set<int> afoo = foo();
In this case, I create a temporary memory space in function foo(), and then
assign it to afoo
by copying. I really want to avoid this copy, any easy way I
can do this in C++11? I think this has to do with the rvalue thing.
OK, update to the question: If I am going to return an object defined by myself, not the vector or set thing, does that mean I should define a move constructor? like this:
class value_to_return {
value_to_return (value_to_return && other) {
// how to write it here? I think std::move is supposed to be used?
}
}
THanks!!!
commercial-grade C++ compilers won't do that: the return statement will directly construct x itself. Not a copy of x, not a pointer to x, not a reference to x, but x itself.
A function can also return objects either by value or by reference. When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function.
Modem C++ compiler will implement: given a type T
:
Check out return value optimization. A modern compiler will optimize this situation, and in straightforward situations like these, no copy will be made on any of the major compilers.
In principle, you could also create your object outside the function, and then call the function and pass the object to it by reference. That would be the old way of avoiding a copy, but it is unnecessary and undesirable now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With