D.Badawi
D.Badawi

Reputation: 175

Dynamically allocated member variable. What's the point?

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.

Upvotes: 0

Views: 1726

Answers (3)

David Haim
David Haim

Reputation: 26506

Let me take some post-modern approach and say "you don't have to worry about it anymore"

use unique_ptr if only the creating-object is incharge of that resource, use shared_ptr if many objects share that resource. use STL containers for all other possible uses.

use new and delete only if you're writing something extremely low-level or implementing a container from scratch. for all other cases, view dynamic memory allocation (via malloc and new) as deprecated.

Upvotes: 1

alain
alain

Reputation: 12047

Reasons to allocate a member dynamically are

  • The size of an array may be non-constant
  • The member could be very large, such that there is not enough memory on the stack
  • The member is polymorphic, as commented by MSalters

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.

Upvotes: 3

Ajay
Ajay

Reputation: 18431

Should it always be deleted in destructor?

Not a necessity - you can free up the memory as soon as the work is done by some other function, if you are sure it won't be used any further. But, you must anyway call this destruction routine from destructor also to avoid memory leak. Ideally, you'd also need to provide another function for ReAllocate the memory.

In short, it all depends on your class and what are you implementing.

Upvotes: 2

Related Questions