C++ 作为对象属性和对象向量的互斥体

C++ 作为对象属性和对象向量的互斥体,c++,c++11,C++,C++11,我正在做一个多线程的书店管理项目。我有一个类,Shelf包含一个互斥对象作为属性。编译时,出现以下错误: error: use of deleted function 'Shelf& Shelf::operator=(const Shelf&)' *__result = *__first; note: 'Shelf& Shelf::operator=(const Shelf&)' is implicitly declared as deleted bec

我正在做一个多线程的书店管理项目。我有一个类,Shelf包含一个互斥对象作为属性。编译时,出现以下错误:

error: use of deleted function 'Shelf& Shelf::operator=(const Shelf&)'
    *__result = *__first;

note: 'Shelf& Shelf::operator=(const Shelf&)' is implicitly declared as deleted because 'Shelf' declares a move constructor or move assignment operator
class Shelf {
我的项目结构如下: 1.这本书有一些字符串,如:名称、类型。。。 2.书架上有:可变互斥体和一个无序的id和Book映射* 3.库具有:工具架对象的向量。 我在这里看到互斥体是不可复制/移动的,所以我遵循了@HowardHinnant answer的说明

typedef std::unordered_map<Id_t, Book *> hash_map_books_t;
class Shelf {

    using MutexType = std::mutex;
    using ReadLock = std::unique_lock<MutexType>;
    using WriteLock = std::unique_lock<MutexType>;

private:
    //ATTRIBUTES

    mutable MutexType m_mutex;
    std::string m_genre;
    hash_map_books_t m_shelf;

public:

    //CONSTRUCTORS & MOVE & COPY & DESTRUCTORS

    Shelf() = default;

    ~Shelf(){
        for (auto b : m_shelf) {
            delete b.second;
        }
        m_shelf.clear();
    }

    Shelf(Shelf &&shelf) noexcept{

        WriteLock rhs_lk(shelf.m_mutex);

        m_genre = std::move(shelf.m_genre);
        m_shelf = std::move(shelf.m_shelf);

    }

    Shelf(const Shelf &a){

        ReadLock rhs_lk(a.m_mutex);
        m_genre = a.m_genre;
        m_shelf = a.m_shelf;
    }
    Shelf& operator=(Shelf &&a) noexcept{

        if (this != &a) {
            WriteLock lhs_lk(m_mutex, std::defer_lock);
            WriteLock rhs_lk(a.m_mutex, std::defer_lock);

            std::lock(lhs_lk, rhs_lk);

            m_genre = std::move(a.m_genre);
            m_shelf = std::move(a.m_shelf);
        }
        return *this;
    }
};

即使不是我问题的目的,我也愿意接受您可以告诉我的其他结构。

正如错误消息所解释的,您需要提供一个副本分配运算符,例如:

Shelf& operator= (const Shelf &a)
{
    if (this != &a)
    {
        WriteLock lhs_lk (m_mutex, std::defer_lock);
        ReadLock rhs_lk (a.m_mutex, std::defer_lock);
        std::lock (lhs_lk, rhs_lk);

        m_genre = a.m_genre;
        m_shelf = a.m_shelf;
    }
    return *this;
}
由于存在用户定义的移动构造函数或用户定义的移动分配运算符,因此有必要进行此操作。你两者都有