sutex作为对象属性和对象的向量
Mutex as object attribute and vector of objects
我正在研究一个带有多个线程的书店管理项目。我有一个shelf((的类,其中包含一个sutex作为属性。当我编译时,我会收到以下错误:
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((有一些字符串,例如:名称,类型...
2.架子((具有:Mutable Mutex和ID和书籍的Unordered_map*
3.库((有:架子对象的向量。
我在这里看到了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;
}
};
,即使不是我问题的目的,我也会为您可以告诉我的其他结构开放。
正如错误消息所解释的那样,您需要提供复制分配操作员,例如:
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;
}
存在用户定义的移动构造函数或用户定义的移动分配操作员的存在使得这是必要的。你们两个。
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 从多个源构造一个对象,包括一个对象向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 对象 C++ 向量的 STL 容器
- 初始化C++中的对象向量
- 从自定义类获取对象向量中的 max 元素
- 如何在 c++ 中打印存档中的对象向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 在 c++ 的构造函数中分配对象向量时出错
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 对象向量是否在堆或堆栈上分配C++?
- 基于不同字段的对象向量的排序功能
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 用rapidjson读取子对象向量
- 尝试使用比较运算符对对象向量进行排序
- 如何用对象向量重载 cin(>>)
- 如何将某个元素从shared_ptr擦除到对象向量?