简体   繁体   English

如何移动 - 构建C ++ STL映射?

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

The following code raises an error under GCC 4.9.3. 以下代码在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. 潜在的错误是use of deleted function 'Movable::Movable(const Movable&)' - 但是AFAICS它不应该试图复制底层的Movable。

As _m has a name, it is a lvalue when used, you have to use std::move : 由于_m有一个名字,使用时它是一个左值,你必须使用std::move

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM