问题描述
我了解到,线程之间进行通信的一种方法是共享一些原子数据结构。例如:
struct Point {
int const x,y;
};
std::atomic<Point> some_point_in_shared_memory{Point{0,0}};
尽管Point::operator=(Point const &)
被删除,但似乎no problem如下调用std::atomic<Point>
的赋值运算符:
some_point_in_shared_memory = Point{1,2};
如何执行此操作?
我可能想到的一种解决方案是使用placement new
在旧对象(显然是it is not exception safe)之上构造一个新对象。还是可以Point
轻松复制吗?
解决方法
来自cppreference:
主std :: atomic模板可以使用任何实例化 满足CopyConstructible和 CopyAssignable。如果以下任何值,则该程序格式不正确 是错误的:
std::is_trivially_copyable<T>::value std::is_copy_constructible<T>::value std::is_move_constructible<T>::value std::is_copy_assignable<T>::value std::is_move_assignable<T>::value
您的T
是不可复制分配的,并且此行
some_point_in_shared_memory = Point{1,2};
格式错误。应该有一个编译器错误。不幸的是,我没有让GCC发出错误或警告(-pedantic -Wpedantic -pedantic-errors -Wall -Werror=pedantic
无效)。