jeudi 22 novembre 2018

Non-copyable elements in a std::vector of std::lists

I have a non-copyable class, simplified as follows:

struct NonCopyable
{
    NonCopyable() = default;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator = (const NonCopyable&) = delete;
    NonCopyable(NonCopyable&&) = default;
    NonCopyable& operator = (NonCopyable&&) = default;
};

I store the objects of this class in various std::lists. At one point I have an empty std::vector of these lists, which I would like to resize to contain a fixed number of empty lists. However, this complains about the lack of a NonCopyable copy constructor, even though (as far as I can see) it shouldn't be trying to construct any NonCopyables!

std::vector<std::list<NonCopyable>> v; // OK
v.resize(4);                           // ERROR
v.emplace_back();                      // ERROR
std::list<NonCopyable> l;              // OK
v.push_back(l);                        // ERROR
v.push_back(std::move(l));             // ERROR

Why is this? Is there any way to do this without making the class copyable?

I'm using VS2017 in case that makes any difference.

Aucun commentaire:

Enregistrer un commentaire