How to create a dynamically allocated array of objects and not use the default constructor?

A dynamically created array of objects should use a non-default constructor, and I consider the problem I am facing as syntax. In my opinion, the fact that I can do it

int * somePtr = new int[5]; 

means i have to do this

 IntegerSet* someSet = new IntegerSet(this->getLength())[5]; 

where IntegerSet is the class I made representing an integer set. this code occurs inside one of the member functions of IntegerSets. When I try to do this, I get the syntax error "cannot convert from IntegerSet to IntegerSet *"

I understand what this means, these two types are not equivalent, but I do not see the difference between what I did in parts 1 and 2, except that part 2 should have a list of arguments as a constructor. So it is in this part of the code that I suspect that I have the wrong syntax

+4
source share
2 answers

new expression allows only initialization by default; you cannot do this in a single new expression . What you could do is allocate raw memory and build objects one at a time by placing new (see this answer in Initializing an array of objects without a default constructor )

Or better yet, don't use C-style arrays. Instead, use some STL container such as std::vector and its constructor, where the second argument is the value that will be used to initialize the elements:

 std::vector<IntegerSet> integers(5, IntegerSet(this->getLength()) ); 
+3
source

There is a simple way out of this problem: add a default constructor to the IntegerSet , which does not receive memory and other resources. This way you can allocate an IntegerSet array with new and then fill each element of the array in the next step.

An even better solution: use std::vector<IntegerSet> and emplace_back() to initialize each element of the array with a different constructor.

0
source