0

From here http://www.cplusplus.com/reference/new/operator%20new[]/, it is unclear to me is it possible to allocate and construct objects with parameters. Like this:

struct MyClass {
  int data;
  MyClass(int k) {} 
};

int main () {
  // allocates and constructs five objects:
  MyClass * p1 = new MyClass[5](1);               // allocate 5 objects, and init all with '1'
}

Which is not work...

tower120
  • 5,007
  • 6
  • 40
  • 88
  • Similar: http://stackoverflow.com/questions/24500164/is-direct-initialization-forbidden-for-array – chris Jul 04 '14 at 18:37

2 Answers2

2

That wouldn't work, but you can use an std::vector<MyClass> for that:

std::vector<MyClass> p1(5, 1);

This will create a vector containing 5 MyClass objects. Note that this works because your single parameter constructor is not explicit. If it were, you would need

std::vector<MyClass> p1(5, MyClass(1));
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

What you wrote does not work, but you could do this since C++11.
Still, better avoid dynamic allocation and go for automatic object.
Also, most times you really should use a standard container like std::array or std::vector.

MyClass * a = new MyClass[5]{1,1,1,1,1};
MyClass b[5] = {1,1,1,1,1};
std::vector<MyClass> c(5, 1);
std::vector<MyClass> d(5, MyClass(1));
std::array<MyClass,5> e{1,1,1,1,1};
Deduplicator
  • 44,692
  • 7
  • 66
  • 118