我有一个带有原子成员变量的类:
struct Foo
{
std::atomic<bool> bar;
/* ... lots of other stuff, not relevant here ... */
Foo()
: bar( false )
{}
/* Trivial implementation fails in gcc 4.7 with:
* error: use of deleted function ‘std::atomic<bool>::atomic(const td::atomic<bool>&)’
*/
Foo( Foo&& other )
: bar( other.bar )
{}
};
Foo f;
Foo f2(std::move(f)); // use the move
Run Code Online (Sandbox Code Playgroud)
移动构造函数应该怎么样?
GCC 4.7不喜欢我的任何企图(如添加std::move()周围other.bar)和净是出奇的安静这里...
我有一个类似下面的课程.
#include <atomic>
static const long myValue = 0;
class Sequence
{
public:
Sequence(long initial_value = myValue) : value_(initial_value) {}
private:
std::atomic<long> value_;
};
int main()
{
Sequence firstSequence;
Sequence secondSequence = firstSequence;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到这样的编译错误,
test.cpp:21:36: error: use of deleted function ‘Sequence::Sequence(const Sequence&)’
test.cpp:5:7: error: ‘Sequence::Sequence(const Sequence&)’ is implicitly deleted because the default definition would be ill-formed:
test.cpp:5:7: error: use of deleted function ‘std::atomic<long int>::atomic(const std::atomic<long int>&)’
Run Code Online (Sandbox Code Playgroud)
这是默认的复制构造函数,赋值opertaor在这种情况下不起作用吗?
PS:我使用的是gcc 4.6.3版
据我所知,复制构造函数必须是T(const T&)或者T(T&).如果我想在签名中添加默认参数怎么办?
T(const T&, double f = 1.0);
Run Code Online (Sandbox Code Playgroud)
这会符合标准吗?
我正在为数据结构编写一个复制构造函数,需要将两个std::atomic<T>成员复制到一个新对象中.虽然在我的用例中该过程不一定必须是原子的,但我希望能够找到最正确的解决方案.
我知道复制构造函数被显式删除,std::atomic<T>以强制用户使用原子接口.
原子(const atomic&)=删除;
我目前正在做的事情是这样的:
SomeObject(const SomeObject& other):
_atomic1(other._atomic1.load()),
_atomic2(other._atomic2.load()) {
...
}
Run Code Online (Sandbox Code Playgroud)
我不相信这个操作是原子的,我也不知道如何制作(没有锁).
有没有办法以原子方式复制这些值(没有锁定)?