I'm totally new to C++. I would like to ask about the following.
If a member variable is dynamically allocated in the constructor. Should it always be deleted in destructor? If so, then how is the variable's lifetime "elongated"? If not, how should memory leak be handled otherwise?
I couldn't find any source to address this issue explicitly.
Reasons to allocate a member dynamically are
But, as Alf already pointed out in a comment, it is preferable to use a smart pointer. This has the advantage that you don't need to explicitly delete
that member in the destructor, and in the case of a shared_ptr
, you can elongate the liftime as needed, the smart pointer takes care of the destruction.