How should I write function parameters to enforce a move rather than a copy?

c++, c++11, move-semantics, parameters

Solution

If you want to support moving and copying, the easiest way would be to pass by value:

Bar(umap m) : bm(std::move(m)) { }

Now you can construct `Bar` from both an lvalue and an rvalue:

umap m;
Bar b1(m);               // copies
Bar b2(std::move(m));    // moves
Bar b3(make_umap());     // moves

If you only want to support rvalues, then use an explicit rvalue reference:

Bar(umap && m) : bm(std::move(m)) { }

The `std::move` is always necessary, since `(m)` is always an lvalue.

Problem

I want to move a large container from a return value into another class using that class' constructor. How do I formulate the parameter to ensure that it doesn't end up being copied? ``` /* for the sake of simplicity, imagine this typedef to be global */ typedef std::unordered_map<std::string, unsigned int> umap; umap foo() { umap m; /* fill with lots of data */ return m; } class Bar { public: Bar(umap m) : bm(m) { } private: umap bm; }; Bar myBar(foo()); // run foo and pass return value directly to Bar constructor ``` Will above formulation trigger the appropriate behavior, or do I need to specify the constructor's parameters as rvalue-references, the way containers do for their own move-semantics? ``` public: Bar(umap&& m) : bm(m) { } ``` or ``` public: Bar(umap&& m) : bm(std::move(m)) { } ``` ...?

Original source