Mohan
Mohan

Reputation: 8863

How can one move-construct a C++ STL map?

The following code raises an error under GCC 4.9.3.

    #include <map>
    using namespace std;

    struct Movable {
        Movable(const Movable&) = delete;
        Movable(Movable&&) = default;
    };

    class Foo {
        const map<int, Movable> m;
        Foo(map<int, Movable>&& _m) : m{_m} {}
    };

The underlying error is use of deleted function 'Movable::Movable(const Movable&)' -- but AFAICS it shouldn't be trying to copy the underlying Movable.

Upvotes: 2

Views: 174

Answers (1)

Jarod42
Jarod42

Reputation: 218323

As _m has a name, it is a lvalue when used, you have to use std::move:

class Foo {
    const map<int, Movable> m;
    Foo(map<int, Movable>&& _m) : m{std::move(_m)} {}
};

Upvotes: 8

Related Questions