-1
在这段代码是std :: swap线程安全,因此它可以从两个执行线程同时调用,或者我需要使用atomic_compare_exchange_weak()而不是swap()吗?比较和交换使用atomic_compare_exchange_weak
如何知道这是否适用于所有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;
};
我知道交换一个指针是矫枉过正,但是这个迁移是一个很好的实践。
这意味着,'std :: swap'是[re-entrant](https://en.wikipedia.org/wiki/Reentrancy_(计算)),不是线程安全的,对不对? – Zereges
@Zereges这个函数不保持任何状态,所以它是线程安全的并且是可重入的。 –