Search code examples
c++c++11atomicmove-semanticslibstdc++

C++11: write move constructor with atomic<bool> member?


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 doesn't like any of my attempts (like adding std::move() around the other.bar) and the net is surprisingly quiet here...


Solution

  • 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> 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( ) )