简体   繁体   中英

How to avoid use of copy-constructor and move constructor in C++

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM