3

I know C++11 has move semantics from this link: Elements of Modern C++ Style

But it does not introduce how to return a vector using move semantics. How to do this?

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Dean Chen
  • 3,800
  • 8
  • 45
  • 70

1 Answers1

9

Like this:

std::vector<std::string> make_a_vector_of_strings()
{
    std::vector<std::string> result;

    // just an example; real logic goes here
    result.push_back("Hello");
    result.push_back("World");

    return result;
}

The operand of the return statement is eligible for copy elision, and if the copy is not elided, the operand is considered for the move-constructor of the return type, so everything is as good as it can be.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I see some posts said using std::vector && as return type, or return move(result). All these confusing me! – Dean Chen Apr 11 '15 at 15:35
  • 2
    @DeanChen: Both of these ideas sound completely wrong. – Kerrek SB Apr 11 '15 at 17:07
  • I think you should qualify that `result` is only moved in the return-statement since it's a local variable / parameter. If `result` was a data member (or global, eww), it would not be moved. – dyp Apr 11 '15 at 22:04
  • @dyp: if `result` weren't a local variable, the code would still Do The Right Thing, since then it would be aliased and we wouldn't want to mutate an aliased value surreptitiously without express request to do so. – Kerrek SB Apr 11 '15 at 22:08
  • Indeed, but I fear that your answer may be misunderstood: One might think that a return-statement always moves its operand. – dyp Apr 12 '15 at 00:02
  • @dyp: Maybe. Once I see the first SO question about someone expecting a move from a return statement when there is none I might start mentioning this. – Kerrek SB Apr 12 '15 at 00:07