0

A class, having an array of atomic objects as one of it's private data member, is desired.

class A {
  vector<atomic<int>> arr;
  public:
    A(int size, int init) : arr(vector<atomic<int>>(size,init)) {} 
      // Error: Deleted 'atomic(const atomic&)' (GCC)
};

Fairly simple, the copy constructor is deleted. All I want to do is initialize each of the entries in arr to init. I am able to do this using pointer and dynamic allocation.

class A {
  atomic<int> *arr;
  public:
    A(int size, int init) : arr(new atomic<int>[size]) {
      for (int i=0; i<size; ++i) arr[i]=init; // Not initialization, but works
    } 
};

But I want to do this using vectors (C++ish way). I tried explicitly assigning to vector elements, but even vector::resize() and vector::push_back() requires a copy ctor.

class A {
  vector<atomic<int>> arr;
  public:
    A(int size, int init) { 
      arr.resize(size); // Error: Deleted 'atomic(const atomic&)' (GCC)
      for (int i=0; i<size; ++i) arr[i]=init;
    }
};

Is there any hack possible or pointer one is the only alternative?

Thank You.

stillanoob
  • 1,279
  • 2
  • 16
  • 29
  • 1
    Why not `arr(size, init)`? – SergeyA Oct 06 '16 at 18:40
  • 2
    [`emplace_back`](http://en.cppreference.com/w/cpp/container/vector/emplace_back) constructs items in place. Unfortunately, because of the potential needed reallocation it also requires T be MoveInsertable, which atomics don't satisfy. – jaggedSpire Oct 06 '16 at 18:40

1 Answers1

4

You may do

A(int size, int init) : arr(size)
{
    for (auto& e : arr) {
        e = init;
    }
}

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Yes, it works. But again, it's not initialization which is originally desired. Can this explicit assignment be avoided? – stillanoob Oct 06 '16 at 18:49