4 ms·
C++ allows zero-overhead abstractions, but in my experience it's pretty idiomatic for "stack" variables to implicitly do heap allocations or similar possibly-ex
by 0xcde4c3db 9y ago
C++ allows zero-overhead abstractions, but in my experience it's pretty idiomatic for "stack" variables to implicitly do heap allocations or similar possibly-expensive operations (acquire mutexes/semaphores, exchange IPC messages, etc.) in their constructors. Maybe this isn't true of modern/Core Guidelines C++, but it's true of a lot of code I've seen.
- ahartmetz 9y agoI agree about internal heap allocations in stack variables. I disagree about other expensive operations happening unpredictably in constructors. If a class does something expensive in its constructor, you can generally tell by the kind of class it is. If you know the difference between identity classes and value classes - value classes may allocate but that's about it. Identity classes may be expensive (i.e. more expensive than baseline, which is writing all the memory they use once) to construct but you can generally tell.
- TheCoelacanth 9y agoThat is very true of modern C++ because the idiomatic way of handling the acquisition and release of all resources is to acquire in a constructor (typically either explicitly for a single resources or implicitly by including another object that acquires resources as a member variable for multiple resources). C++ doesn't completely free you from considering whether a type allocates memory on the stack or on the heap, but it does let you limit which code needs to concern itself with where values are allocated to a very small portion of the code. Most code written to work against a std::vector will also work against a std::array unless it is relying on the ability of a std::vector to dynamically resize.
- klmr 9y ago> C++ doesn't completely free you from considering whether a type allocates memory on the stack or on the heap You’re completely right but the way this is phrased shows a common misconception about C++/RAII: it was never about freeing the programmer from considering how to manage memory. Rather, it was about automating the mechanics behind these considerations, and adding a layer of type safety (which C++11 tremendously improved). If you don’t want to think about memory management, use a garbage collected language (but accept that it doesn’t scale to all scenarios). C++ forces you to think about resource management, it just makes the implementation of resource management vastly easier than C.