3 ms·
If you `new` something, you must `delete` it exactly once. The constructor and destructor of a class are ideal for this because they are paired like this. But
by MauranKilom 7y ago
If you `new` something, you must `delete` it exactly once.
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".