2

I have the next tiny code:

#include<atomic>
#include<deque>
int main() {
    std::deque<std::atomic<int>> q;
    q.push_back(0);
}

It doesn't work. It is tested with g++ 4.9.2 and g++ 6.3.0. The compilers produce a bit too long error message which essential part contains words:

error: use of deleted function ‘std::atomic::atomic(const std::atomic&)

vollitwr
  • 429
  • 2
  • 8

1 Answers1

2

As explained in this question atomics cannot be copied.

Some dynamic sized containers require their content to be copiable so as to be able to increase the capacity. This is the case for vector and deque for instance.

Guillaume Gris
  • 2,135
  • 17
  • 34
  • This explanation doesn't look logical for me because 0 is non-atomic constant. 0 is used to create a new atomic object, I don't observe any copy operation there. – vollitwr Oct 21 '17 at 08:54
  • True, there is no copy performed here. But on a general basis, there might be. If you push_back twice for instance, the backing buffer of the deque might be reallocated, this will require a copy of an atomic_int already in the queue. – Guillaume Gris Oct 21 '17 at 09:23
  • IMHO this problem maybe resolved - deque just needs a specialization for the atomic objects. – vollitwr Oct 21 '17 at 10:03
  • It could trivially for a fixed size deque. But for a dynamic sized one, it probably can't for the exact same reasons an atomic can't be copied. At least not with all the requirements the standard imposes on a deque – Guillaume Gris Oct 21 '17 at 10:06
  • Why not to use move? – vollitwr Oct 21 '17 at 10:49
  • Atomics cannot be moved for the same reason they cannot be copied. However, you could do a std::deque> that would meet your expectations. Not sure what is you use case though – Guillaume Gris Oct 22 '17 at 11:33