Peter Jankuliak
Peter Jankuliak

Reputation: 3619

Can I allocate `std::array` on stack without knowing size at compile time?

When allocating on the stack, I don't necessarily need to know the size of a C array being allocated at compile time. i.e. I can do this:

void foo(size_t s) {
    uint8_t bar[s]; // `s` not known at compile time
    some_func_that_uses_bar(bar, sizeof(bar));
}

However, to be less error-prone, it feels I should be able to do this with C++ std::arrays as well, yet I haven't been able to figure out how (nor whether it's even possible).

Upvotes: 3

Views: 1192

Answers (3)

Oblivion
Oblivion

Reputation: 7374

If you want to allocate array in stack you can use Smallvector from llvm. for small size it starts from stack and then if needed with push_back it goes to heap memory:

llvm::SmallVector<int, 5> smallVector;
for(int i = 0; i < 5; i++) { 
    smallVector.push_back(i); 
} // No heap allocations have been performed up to this point.
smallVector.push_back(6); // heap allocation now

Upvotes: 1

eerorika
eerorika

Reputation: 238301

i.e. I can do this:

void foo(size_t s) {
    uint8_t bar[s]; // `s` not known at compile time
    some_func_that_uses_bar(bar, sizeof(bar));
}

No, you cannot do this in C++. The size of an array must be a compile time constant.

it feels I should be able to do this with C++ std::arrays as well

No, this is not possible using std::array either.

If the size of the array is not known at compile time, you must allocate it dynamically. Typical solution is to use a vector.

If you expect the size to be small, a possible optimisation is to use a custom vector type that uses a small buffer optimisation to avoid dynamic allocation when the size does not exceed a compile time defined limit.

Upvotes: 0

Sneftel
Sneftel

Reputation: 41454

No, you can't. C has added special support for variable-length arrays, but C++ has not. You can get a similar effect using alloca(), but that's not a standard function and will require additional work if you're using it with a class requiring a specific alignment, and requires you to manually invoke the constructors and destructors.

For that use case, a normal C++ programmer would use std::vector.

Upvotes: 6

Related Questions