SwiftMango
SwiftMango

Reputation: 15284

Return rvalue reference from move is not persisted

I have this code:

string&& getString() {
    string s {"test"};
    return move(s);
}

and I tried to output:

cout << getString() << endl;

It gives me empty output.

When I use:

string getString() {
    string s {"test"};
    return move(s);
}

It works.

My question:

  1. Why the first one is not working? I moved the reference so the local object should not be destroyed?

  2. Does the second one do "copy" (not considering RVO)?

Upvotes: 0

Views: 93

Answers (1)

billz
billz

Reputation: 45410

Why the first one is not working? I moved the reference so the local object should not be destroyed?

string&& getString() {
    string s {"test"};  // s is a local variable
    return move(s);     // move doesn't really move object, it turns the object to rvalue
}

You are returning an rvalue reference to a local non-static object.
An rvalue reference is a reference, and returning it while referring to a local object means that you return a reference to an object that doesn’t exist any more. Whether std::move() is used doesn’t matter, because std::move doesn't really move object, it turns the object to rvalue

Does the second one do "copy" (not considering RVO)?

Compiler should consider RVO first then move(Since C++11), otherwise it should copy. see this as well.

You just need to write:

string getString() {
  string s {"test"};
  return s;
}

Upvotes: 1

Related Questions