I'd like to know if there is a standard way to allocate a variable number of objects on the stack that all today's C++ compilers support. Supposing I have a class Foo
with a non-trivial public constructor that takes 0 arguments and I want to allocate 10 instances of this class on the heap, then I could use the operator new[]
in C++ like this:
function doSomething() {
Foo * foos = new Foo[10];
...
}
If the number of objects to allocate is not known at compile time, I could still use the operator new[]
in a similar fashion:
function doSomething(size_t count) {
Foo * foos = new Foo[count];
...
}
So, if I decide to allocate 10 instances of my class on the stack rather than on the heap, I'd use a regular array definition:
function doSomething() {
Foo array[10];
Foo * foos = array;
...
}
or probably just Foo foos[10];
in case I don't need to reassign foos
later, ok.
Now, if the number of objects I want to allocate on the stack is only known at runtime, I use... what? The only way I can think of to dynamically allocate contiguous memory on the stack is calling the non-standard intrinsic function alloca
, but I don't know what to do with objects that need initialization.