3
#include <vector>
using namespace std;

struct TempData {
    vector<int> data;
    TempData() {
        for(int i = 0; i < 100; i++) data.push_back(i);
    }
    // vector<int> GetData() { // function 1
    //  return move(data);
    // }
    vector<int>&& GetData() { // function 2
        return move(data);
    }
};

int main() {
    vector<int> v;
    {
        TempData td;
        v = td.GetData();
    }
}

What is the difference between function 1 and function 2?

Will function 1 construct a temp vector with move(data) and then assign the temp vector to v?

No more details to add...

chaosink
  • 1,329
  • 13
  • 27
  • One function returns a new vector, the other does not. – Kerrek SB Dec 11 '17 at 16:47
  • You should consider overloading on reference qualifiers. See https://stackoverflow.com/questions/21052377/whats-a-use-case-for-overloading-member-functions-on-reference-qualifiers – François Andrieux Dec 11 '17 at 16:47
  • If you need to do this, you should consider passing the object in, then you don't need it handed back. – keith Dec 11 '17 at 17:11

1 Answers1

5

In your little test case there is likely no difference. The extra temporary object will almost certainly be elided. And the v in main will hold the contents of the member variable.

But in the general case:

Version 1 will definitely leave the member data in some unspecified "empty" state. Even when the function return value is discarded.

Version 2 may leave the member in some unspecified empty state, or it may not. For instance, if the function is called and its return value discarded, the member will be unchanged. This is why it can be said that std::move by itself doesn't move anything.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458