4 ms·
You mean C++ programmers allocate n object on the heap even when its lifetime is the same as the scope of the containing block ? Unless its such a large huge o
by srean 11y ago
You mean C++ programmers allocate n object on the heap even when its lifetime is the same as the scope of the containing block ?
Unless its such a large huge object that stackoverflow is a possibility I cant imagine why would one do that.
- petke 11y agoMany programmers have this idea. Oh, this is a big object. I better wrap it in a smart pointer to avoid doing expensive copies when I pass it around. They do it as an optimisation. However because of named return value optimisation and move constructors no expensive copies are done when passing stack values to and from functions. Using smart pointers is actually slower (because of the indirection and reference counting).
- yongjik 11y agoI 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.
- CyberDildonics 11y agoNo one who cares about performance enough to be using C++ would do something like this. Allocating on the heap when not necessary is a sign of a dangerous amateur.