twar
twar

Reputation: 71

Aggregate initialization and deleted copy constructor aka non-copyable obejcts as fields

Is there a way to initialize below vector?

struct Test {
std::atomic_bool is_enabled;
int age;};

int main()
{
    std::vector<Test> tests{
        Test{false, 42},
        Test{true, 77}
    };
}

The most obvious (for me at least) way doesn't work. The problem is std::atomic_bool is_enabled deleted copy constructor and I have no idea what to do. :)

Upvotes: 1

Views: 105

Answers (2)

sam
sam

Reputation: 43

If you want just a read only after initialization atomic_bool then you can do something like this:

#include <iostream>
#include <atomic>
#include <vector>

using namespace std;


struct Test {
const atomic_bool& is_enabled = true;
int age;
};

int main()
{

  vector<Test> v2 = { { true, 42}, {false, 76}};
  cout << v2[1].is_enabled << " " << v2[1].age << endl;

  return 0;
}

Upvotes: 0

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17434

You can implement a copy-constructor for your Test type. You just can't rely on copy-construction for atomics nor - in consequence - an autogenerated copy constructor of Test.

Beware though: What you're doing seems brittle. Why do you think that the one member needs to be atomic, but others don't? Who protects the vector itself?

Upvotes: 3

Related Questions