简体   繁体   中英

Allocating a variable number of objects on the stack in C++

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.

What about:

std::vector<MyObject> myObjects;

int runtimeCalculatedSize = sophisticatedRuntimeSizeCalculationMethod();

myObjects.resize(runtimeCalculatedSize,MyObject());

Well, if lazy, and not worried about portability, I use: Foo array[n]; This is standard C code, but has been removed from the C++ standard. But since most compilers do both, most compilers have it. The canonical way is to declare a std::vector of your type of the desired length.

std::vector<Foo> foos(count);

But, doing that won't strictly put the data on the stack, is there any reason why using the stack is important to you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM