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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With