Heap allocation of struct without copy, move and default constructor

122 Views Asked by At

I have a struct that cannot be neither copied nor moved, nor it has a default constructor:

struct Data {
  int a;

  Data(const Data&) = delete;
  Data& operator=(const Data&) = delete;

  Data(Data&&) = delete;
  Data& operator=(Data&&) = delete;

  Data(int i):
    a{i}
  {}
};

I would like to allocate in the heap an array of these struct constructing all of them with the same constructor. I managed to accomplish this in the following way:

Data* ppd = (Data*)::operator new(10 * sizeof(Data));

for (auto p = ppd; p < ppd + 10; ++p)
  new(p) Data{45};

however I'm very unsatisfied with that. Obviously I have a look to this reference, but I could not find what I was looking for.

Do you have any suggestion to accomplish my task in a more expressive way?

2

There are 2 best solutions below

0
0xbachmann On

Is it a possibility for you, to use std::list instead of an array type?

Some containers like std::vector won't work because the data might get reallocated, which is not possible, as the move constructor is deleted. std::list's data will not get reallocated.

Because push_back uses some default constructors as well emplace_back could be used instead to call your custom constructor.

std::list<Data> list;
for (unsigned i = 0; i < 10; ++i) {
    list.emplace_back(45);
}
0
user12002570 On

You can use macro and boost as shown below:

#include <boost/preprocessor/repetition/enum.hpp>
#define Create_B_List(...) {__VA_ARGS__}
#define Repeat(P, A, X) X
#define Create(Count, Value) Create_B_List(BOOST_PP_ENUM(Count, Repeat, Value))

int main()
{  
    Data *p = new Data[]Create(10, 45);     
} 

Working demo