I now recall that when I programmed in C, my code never used malloc() directly.
The library functions probably used malloc to some extent, but malloc was advanced feature. Alexandrescu confirmed my experience and said that c++ programmers usually make rather few malloc() calls, each time requesting a large chunk. Instead of malloc, I used mostly local variables and static variables. In contrast, C++ uses heap much more:
- STL containers are 99% heap-based
- virtual functions require pointer, and the target objects are usually on heap, as Alexandrescu said on P78
- pimpl idiom i.e. private implementation requires heap object, as Alexandrescu said on P78
- the c++ reference is used mostly for pass-by-reference. Pass-by-reference usually works with heap objects.
In contrast, C++ uses small chunks of heap memory.
Across languages, heap usage is is slow because
- In general OO programming uses more pointers more indirection and more heap objects
- heap allocation is much slower than stack allocation, as Stroustrup explained to me
- using a heap object, always always requires a runtime indirection. The heap object has no name, only an address !
- In Garbabe-Collected languages, there’s one more indirection.