I have a function
struct foo {
std::vector<int> v;
};
foo func();
will the vector inside foo be moved or copied when returning from the function?
It will be moved.(*)
Since you do not provide an explicit move constructor for your foo
class, the compiler will implicitly generate one for you that invokes the move constructor (if available) for all the members of your class. Since std::vector
defines a move constructor, it will be invoked.
Per Paragraph 12.8/15 of the C++11 Standard:
The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members. [...]
Also notice, that the compiler is allowed to elide the call to the copy/move constructor of your class when returning an object by value. This optimization is called (Named) Return Value Optimization.
(*) I am assuming here that your use case is to create a local object with automatic storage inside foo()
and return it.
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