by jb1991 · 6y ago · 0 comments
Of course you can avoid these problems very easily, but you have to be bitten by them first to know how easy they are to write.
Another is to ‘emplace’ straight into a container. When the container is deleted so are the objects.
A third is to use `std::make_shared<foo>(1, “bar”)` or std::make_unique.
The constructor and destructor of a class are ideal for this because they are paired like this. But if your class does (memory) resource management like this, it should only do resource management, else it would violate the single responsibility principle.
This naturally leads to classes that are solely about resource management, where you only express the intended ownership (e.g. unique or shared) and this dedicated class ensures every `new` is matched with a `delete`. Those of course exist in the standard library (since C++11): `std::unique_ptr` and `std::shared_ptr`.
Similar story for arrays: Use `std::vector` if you need a dynamically sized array. It will do all the bookkeeping and memory management you'd have to do with `new T[N]` but it does it right.
It's not about avoiding heap allocation, despite the association that several people are bringing up here. It's about "express and abstract the resource management strategy instead of reimplementing it everywhere and obscuring it to readers".
The idea of needing to employ the standard library to avoid using a core feature of the language seems... interesting? I guess.
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.
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.