3 ms·
'new' allocates an object on the heap, where it is prone to being leaked. Direct allocation on the stack (and maybe moving to the caller function if needed) ke
by kitd 7y ago
'new' allocates an object on the heap, where it is prone to being leaked.
Direct allocation on the stack (and maybe moving to the caller function if needed) keeps everything local and ensures destructors are always called when the stack unwinds.
- Gene_Parmesan 7y agoRight, I guess the thought of never having any heap-based allocation just seems... curious to me, I guess. I have lots of C# (and Java, and Python, and...) experience, and a fair amount of C experience, but I've managed to skip past C++, so many of the idioms I see in modern C++ are fascinating for me.
- hellofunk 7y agoThis isn't really the right concept. Lots of objects must be on the heap, as the stack cannot contain them. The question isn't to avoid putting objects on the heap, it's to avoid the use of "new" to put them on the heap. Modern C++ encourages avoiding manually using "new" and relying on smart pointers for that, as they will automatically call "delete" and avoid a large class of memory leaks from heap usage. Note that member objects are often on the heap without using any smart pointers or use of "new" simply because they inherit the memory area from their enclosing object, and I've see many inexperienced C++ devs manually allocate memory for these objects unnecessarily.
- kitd 7y agoThanks. Your answer captures the nuances much better than mine. I was concentrating simplistically on the difference between heap and stack allocation, but that misses a lot of the common usage & idioms.