1

Given a simple class MyClass with a constructor that accepts two int, how can I initialize an array of MyClass in the heap?

I've tried

MyClass *classes[2] = { new MyClass(1, 2),
                        new MyClass(1, 2) };

But this doesn't seem to work. Thanks

4
  • 1
    The code you posted compiles. Commented Nov 3, 2011 at 23:49
  • The array is on the stack though, with pointers on the heap Commented Nov 4, 2011 at 15:51
  • 1
    @MooingDuck: No: the pointers are on the stack, and the objects are on the heap. Commented Nov 4, 2011 at 15:55
  • @KerrekSB: I wrote it wrong. The array of pointers is on the stack, the objects are on the heap. Either way, he says that isn't what he wants. Commented Nov 4, 2011 at 16:07

1 Answer 1

1

Use the std::allocator<MyClass> for this.

std::allocator<MyClass> alloc;
MyClass* ptr = alloc.allocate(2);  //allocate
for(int i=0; i<2; ++i) {
    alloc.construct(ptr+i, MyClass(1, i)); //construct in C++03
    //alloc.construct(ptr+i, 1, i); //construct in C++11
}

//use

for(int i=0; i<2; ++i) {
    alloc.destroy(ptr+i); //destruct
}
alloc.deallocate(ptr); //deallocate

Note that you don't have to construct all that you allocate.

Or, better yet, just use std::vector.

[EDIT] KerrekSB suggested this as simpler:

MyClass** ptr = new MyClass*[3];
for(int i=0; i<4; ++i)
    ptr[i] = new MyClass(1, i);

//use

for(int i=0; i<4; ++i)
   delete ptr[i];
delete[] ptr;

It's slightly slower access, but much easier to use.

Sign up to request clarification or add additional context in comments.

7 Comments

@KerrekSB: Do you another way to construct an array of objects with varying parameters? I can't think of one. (Not that there isn't, I just can't think of it)
Well, the OP's code is actually correct and does basically that, so I'm not sure where the problem is now...
@KerrekSB: Since a local, fixed size (array (of pointers) on the stack pointing at (objects on the heap)) wasnt what he wanted, he must want an actual (dynamic array of (objects on the heap)).
We clearly need parentheses around those sentences :-) Well, the OP should specify her needs; as it stands, I'm not sure what the problem is.
I actually used to parenthesize sentences like that, until people told me to knock it off and rewrite them so they make sense the first time.
|

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.