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...

1

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

6 Comments

But it construct it one, by one? I don't need vector.
@tower120 Yes, just like when you instantiate an array.
I have to do this MyClass * p3 = static_cast<MyClass*> (::operator new (sizeof(MyClass[5]))); And than call constructor explicitly for each object?
@tower120 No, you do what I told you to do in my answer.
I have pool object implementation that use C native arrays. I create bunch of objects at once. Now I want to create initialized objects.
|
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};

3 Comments

Looks good, but what about variable number of instances and per object arguments? :)
@tower: In that case, hope you can default-construct them. Or it won't work at all.
Well, lets consider we don't have default constructor. Than I have to iterate each constructor. Right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.