【问题标题】:How can one move-construct a C++ STL map?如何移动构建 C++ STL 映射?
【发布时间】:2016-04-06 12:25:25
【问题描述】:

以下代码在 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} {}
    };

基础错误是use of deleted function 'Movable::Movable(const Movable&amp;)'——但 AFAICS 不应该尝试复制基础 Movable。

【问题讨论】:

    标签: c++ stl move-semantics move-constructor


    【解决方案1】:

    由于_m有名字,所以使用时是左值,所以必须使用std::move

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

    【讨论】:

      猜你喜欢
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多