c++c++17noncopyable

Error setting up unordered_map with non copying-able type with gcc 8.4


See here: https://godbolt.org/z/MW3jW6

Using gcc 8.4 (8.3 in godbolt) my code is failing to compile. With gcc 10.x it seems to compile ok. But I can't figure out what the error is telling me exactly...

Here is the code for reference:

#include <mutex>
#include <condition_variable>
#include <iostream>
#include <unordered_map>

class non_copy
{
public:
    non_copy() = default;
    non_copy(non_copy&&){}
    non_copy(non_copy&) = delete;
private:
    std::mutex m;
    std::condition_variable cv;
};

class item
{
public:
    item() = default;
    item(item&&){}
private:
    non_copy  m_item; // Works if I remove this
};

bool test()
{
    // does not work
    std::unordered_map<int, item> map; // Error here
    map.emplace(1, item());

    // Works ok
    std::unordered_map<int, std::string> map2;
    map2.emplace(1, "test");
    return true; 
}

int main()
{
    std::cout << "test" << std::endl;
    return test();
}

If I remove the non_coom m_item from item class then it compiles. I figured that I just needed to create move constructors, but that was not enough. map.emplace - so I read - should take rvalue refs (move c'tor) as parameters. so I think I just got a bit confused here.

What I want to be able to do is just insert new items into the map - I don't care about coping the contents - so the mutex and condition var will just be default constructed.

Note: see the error I get in the link - its quite large, but I can copy it into here if needed


Solution

  • Your copy constructor (with const), even if legal is unusual, and appears to be problematic.

    Use regular one:

    non_copy(const non_copy&) = delete;