12

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?

8
  • 4
    No, it will be moved. Commented Feb 25, 2013 at 19:04
  • 2
    It totally depends on what happens inside func. Commented Feb 25, 2013 at 19:04
  • @BoPersson Not quite, as that question is about returning a vector, while this is about returning a struct with the default move constructor and a vector member. Commented Feb 25, 2013 at 19:05
  • @delnan - No difference. The other question is about returning values in general, and covers this case. Commented Feb 25, 2013 at 19:07
  • 2
    @BoPersson One thing that matters here, which I did not find anywhere in that question, is whether moving a struct without user-defined move constructor moves the members or copies them. I don't doubt this too has been asked and answered before, but the specific question you link to doesn't quite cut it IMHO. Commented Feb 25, 2013 at 19:10

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It won't be moved if the foo it returns is perhaps a foo with static storage duration. There's probably some other cases too. But yes, I agree with you for the case that the asker is probably asking about.
@sftrabbit: OK, that's correct. I assumed that he wanted to returned a local object with automatic storage. Edited, thank you.
@BoPersson: I did mention that, although not RVO explicitly. I will do it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.