Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move semantic and struct [duplicate]

Tags:

c++

c++11

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?

like image 824
yngccc Avatar asked Feb 25 '13 19:02

yngccc


1 Answers

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.

like image 126
Andy Prowl Avatar answered Oct 26 '22 07:10

Andy Prowl