riv
riv

Reputation: 7343

std::map with only move constructor available

I have a class with private constructor (that my container class can access), deleted copy constructor, and default move constructor. How can I use it in a 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_;
};

Using emplace(key, Item(value)) doesn't work, because it tries to copy construct the item. Wrapping Item in std::move has the same effect. Using piecewise_construct doesn't work because the map (or pair) tries to use normal constructor, which is private.

Upvotes: 1

Views: 1520

Answers (1)

Rakete1111
Rakete1111

Reputation: 49028

I have a class with private constructor (that my container class can access), deleted copy constructor, and default move constructor.

Wrong, you do not have a defaulted move constructor. You don't get an implicit move constructor if you declare a copy constructor. You'll need to explicitly default the move constructor to get one:

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);
};

Now you can use:

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

for example to insert an entry.

Upvotes: 9

Related Questions