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?
Is it a possibility for you, to use
std::listinstead of an array type?Some containers like
std::vectorwon'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_backuses some default constructors as wellemplace_backcould be used instead to call your custom constructor.