C ++ 11:使用atomic< bool>编写move构造函数成员? [英] C++11: write move constructor with atomic<bool> member?

查看:117
本文介绍了C ++ 11:使用atomic< bool>编写move构造函数成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有原子成员变量的类:

I've got a class with an atomic member variable:

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

移动构造函数应该是什么样子?

How should be move constructor look like?

Gcc 4.7不喜欢我的任何尝试(例如在other.bar周围添加std::move()),并且这里的网络令人惊讶地安静...

Gcc 4.7 doesn't like any of my attempts (like adding std::move() around the other.bar) and the net is surprisingly quiet here...

推荐答案

由于您要移动other,因此没有其他人可以访问它.因此,无论它是不是原子的,从其bar读取都是安全的.

Since you're moving other, no one else will access it. So reading from its bar is safe, wether it's atomic or not.

atomic<T>只有两个构造函数,一个是默认的(),另一个是(T).因此,您的代码看起来应该可以编译.如果没有,如果您将other.bar静态广播到T,强制使用(T)构造函数,会发生什么情况?

atomic<T> only has two constructors, one being the default (), the other being (T). So, your code looks like it should compile. If it doesn't, what happens if you static_cast other.bar to T, enforcing the (T) constructor to be used?

: bar( static_cast< bool >( other.bar ) )

或者等于,也许不太丑:

or which is equal to, and perhaps less ugly:

: bar( other.bar.load( ) )

这篇关于C ++ 11:使用atomic&lt; bool&gt;编写move构造函数成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆