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

时间:2019-05-04 14:12:38

标签: 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 because 'Shelf' declares a move constructor or move assignment operator
class Shelf {

我的项目结构如下:
1. Book()具有一些字符串,例如:name,genre ......
2. Shelf()具有:可变互斥体以及id和Book *的unordered_map *
3. Library()具有:Shelf对象的向量。
我在这里How should I deal with mutexes in movable types in C++?看到互斥锁不是可复制/不可移动的,所以我遵循了@HowardHinnant答案的说明。

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

即使这不是我提出这个问题的目的,我也乐于接受您可以告诉我的其他结构。

1 个答案:

答案 0 :(得分:1)

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

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

用户定义的移动构造函数或用户定义的移动分配运算符的存在使此操作必要。你们两个都有。