Reputation: 21
I'm getting some problem of classes implementation for a C++ project. Here's the code:
A {
private:
std::atomic<bool> flag;
std::atomic<int> value;
public:
A(){}
};
class B{
private:
std::vector<A> vett;
public:
B(){}
void add_A(A a){
vett.push_back(a);
}
};
int main() {
// Write C++ code here
B b{};
return 0;
}
I know that compiling errors are caused by std::atomic, cause it isn't copy-constructible, nor copy-assignable and class A has std::atomic as attributes. Unfourtunately class A should be a thread-safe class, so I need to use std::atomic or std::mutex (that is also not copyable). By reading other question, to overcome this problem I may create a wrapper struct for an std::atomic, but in this way atomicity would be compromised, so what would be another possible solution?
Upvotes: 0
Views: 559
Reputation: 19213
A
can be made both copyable and moveable by explicitly copying the current values of the atomic members. Of course none of those methods are thread-safe.
struct A{
std::atomic<int> m_member{false};
A()=default;
A(const A& other):m_member(other.m_member.load()){}
A(A&& other):m_member(other.m_member.load()){
// Move other members
}
A& operator=(const A& other){
if(&other!=this){
// De-init current members.
this->m_member=other.m_member.load();
// Copy other members.
}
return *this;
}
A& operator=(A&& other){
if(&other!=this){
// De-init current members.
this->m_member=other.m_member.load();
// Move other members.
}
return *this;
}
};
Upvotes: 2