在这段代码中std :: swap线程是安全的,所以它可以同时从两个执行线程调用,还是需要使用atomic_compare_exchange_weak()而不是swap()?
我如何知道这是否适用于所有CPU?如果它只适用于Intel CPU,我很高兴。
#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;
};
我理解交换指针是一种过度杀伤,但这种迁移是很好的实践。
答案 0 :(得分:0)
只要不同的线程将不同的对象传递给它,是
std::swap
线程安全的,因此可以同时从两个执行线程调用
std::swap
就是线程安全的。否则会出现竞争条件。