如何解决如何为不可变类型实现std :: atomic <T> :: operator =?
我了解到,线程之间进行通信的一种方法是共享一些原子数据结构。例如:
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
无效)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。