只有移动构造函数可用的std :: map

时间:2018-07-30 15:13:37

标签: c++

我有一个带有私有构造函数的类(我的容器类可以访问),已删除的副本构造函数和默认的move构造函数。如何在std::map中使用它?

class Item {
public:
    Item(const Item&) = delete;
private:
    friend class Storage;
    Item(int value);
};

class Storage {
public:
    void addItem(int key, int value) {
        // what to put here?
    }
private:
    std::map<int, Item> items_;
};

使用emplace(key, Item(value))不起作用,因为它试图复制构造项。在std::move中包装项目具有相同的效果。使用piecewise_construct不起作用,因为映射(或对)尝试使用私有的常规构造函数。

1 个答案:

答案 0 :(得分:7)

  

我有一个带有私有构造函数的类(我的容器类可以访问该类),已删除的副本构造函数和默认的move构造函数。

错误,您没有默认的move构造函数。如果声明复制构造函数,则不会获得隐式的move构造函数。您需要显式地默认move构造函数才能获得一个:

class Item {
public:
    Item(const Item&) = delete;
    Item(Item&&) = default;

    // Might be a good idea to declare the two assignment operators too
    Item& operator=(const Item&) = delete;
    Item& operator=(Item&&) = default;
private:
    friend class Storage;
    Item(int value);
};

现在您可以使用:

items_.emplace(key, Item(value));

例如插入一个条目。