The returned class or struct may or may not be copied, depending if the compiler uses copy elision. See the answers to What are copy elision and return value optimization?
In short, whether it is copied or not depends on a number of things.
You can of course avoid a copy by returning a reference. In the case of your example, returning a reference is invalid (though the compiler will allow it) because the local struct is allocated on the stack, and therefor the returned reference refers to a deallocated object. However, if the object was passed to your function (directly or as a member of an object) you can safely return a reference to it and avoid copy-on-return.
Finally, if you cannot trust copy elision and you want to avoid copies, you can use and return a unique_ptr
instead of a reference. The object itself will not be copied, although the unique_ptr
itself may or may not be (again, depending on copy elision!). Copying/moving a unique_ptr
is however very cheap if copy elision of the unique_ptr
does not happen for some reason.
Here is an example using unique_ptr
:
#include <memory>
struct A {
public:
int x;
int y;
A(int x, int y) : x(x), y(y) {
}
};
std::unique_ptr<A> returnsA() {
return std::make_unique<A>(3, 4);
}
int main() {
auto a = returnsA();
}
Note that you must (unfortunately) declare a constructor for your struct, or else make_unique
will not compile due to inadequacies of C++.