4 ms·
I don't think C++ supports variable length arrays? So, if you want to allocate N objects, where N is not known at compile time, (I think) you have to use heap
by yongjik 11y ago
I don't think C++ supports variable length arrays?
So, if you want to allocate N objects, where N is not known at compile time, (I think) you have to use heap allocation anyway. Normally I just use vector<>, and call reserve() if I feel like extra performance-y. Sure, it's much slower than C99-style variable length arrays, but 99% of the time it's still fast enough.
More importantly, it plays nice with other C++ functionalities. For example, zero-copy construction using emplace_back() inside a for loop. (And if you throw an exception in the middle you're guaranteed that destructors are called exactly for those that are already constructed.)
- en4bz 11y ago> I don't think C++ supports variable length arrays? VLAs are not part of the standard but GCC supports them. Clang however does not, at least not without a compiler flag I think.
- petke 11y agostd::array exists. But it isnt variable length. We might get a dynarray in the next standard. I saw a standards committee panel talk where someone asked about it. Ville Voutilainen promised to write standards proposal. I dont miss it much. Usually std::array does what I want.
- srean 11y agoMy question was regarding whether its the norm that C++ programmers use the heap when stack would have sufficed. Parent seemed to be hinting that they do. And, yeah its disappointing C99 arrays did not make it to C++, one can use alloca to live a little dangerously, better to wrap it so that it allocates on the heap only if more than a certain size has been asked for. Too bad there is no portable way to find out how much stack space does the current process still have. There should have been a system call for that.
- CyberDildonics 11y agoYou can still use alloca in C++
- srean 11y agoYes and I have at times, but its living a little dangerously. Even if it returns a non-null pointer it does not mean you can write there safely.