1

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, didn't realize the difference. Works perfectly now with either form. Emplace is probably better in your example, though?
You may want to also = delete copy assignment and = default move assignment.
Fair enough, though the map doesn't seem to need move assignment so I'll just disable the copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.