jeudi 23 juin 2016

compare and swap using atomic_compare_exchange_weak

In this code is std::swap thread safe so it can be called from two execution threads at the same time or do I need use atomic_compare_exchange_weak() instead of swap()?

How do I know if this will work on all CPUs? I am happy if it just works on Intel CPUs.

#include <utility>
class resource {
    int x = 0;
};
class foo
{
    public:
        foo() : p{new resource{}}
        { }
        foo(const foo& other) : p{new resource{*(other.p)}}
        { }
        foo(foo&& other) : p{other.p}
        {
            other.p = nullptr;
        }
        foo& operator=(foo other)
        {
            swap(*this, other);
            return *this;
        }
        virtual ~foo()
        {
            delete p;
        }
        friend void swap(foo& first, foo& second)
        {
            using std::swap;
            swap(first.p, second.p);
        }
    private:
        resource* p;
};

I understand it is overkill to swap a pointer, but this migth be good pracise.

Aucun commentaire:

Enregistrer un commentaire