1

Does the memory allocated by class pointers get freed by the class destructor once the class method/function goes out of scope? Or do I need to manually free the memory allocated by the pointer (C++). For example, here's a snippet of some simple code :

double * const  Area()
{
  double * Area = new double;
  *Area = itslength*itswidth;
  return Area;
  //itslength and itswidth are private class variables
}

So in this example, do I have to free the memory allocated by the Area pointer, or does the class destructor do this by default once the function returns/goes out of scope? If I have to manually free memory, can you modify my code to free the memory?

  • 2
  • The memory allocated by new is on the heap and is not freed automatically upon return. The caller will have to delete it. The memory use by the pointer (the address) is freed upon return, like all local variables. – Jean-Claude Arbaut Aug 2 at 5:19
  • As a side note: Your code is very hard to read - you are e.g. creating a double* local member which has the same (identical) name as the function is is defined in. Do your codevelopers (and your future self) a favor by following some basic naming conventions (which ones exactly is a question of personal preferences, you could e.g. use Google's as a starting point and pick&choose the ones you find useful/sensible/good) – CharonX Aug 2 at 13:31
2

Things allocated using new are not automatically deleted. There needs to be a corresponding delete somewhere in your code. This can be very error-prone and is best avoided.

If you must use new and delete, try to adopt an RAII approach - the new can only appear in a constructor, and the corresponding destructor always has the matching delete.

If you want a collection of things, use one of the standard C++ collection classes, as they tidy up behind themselves - but take great care with collections of pointers, as you still need to delete the things being pointed to.

Alternatively, various pointer management classes have been added to C++ over the years, which do tidy up behind themselves. See the answer by xtofl.

2

When you're starting with C++, shun away from anything telling you to use new. You most probably do not need it.

Memory management is very error prone, and has been solved by more modern approaches. Look up "value semantics" and RAII. And only when you really need dynamically allocated memory, find out what std::unique_ptr<double> can do for you.

For the function you wrote, no dynamic memory is needed:

auto area() {
  return itslength * itswidth;
}

And finally: yes: the destructors of all the object's member variables are called after the object's destructor has been called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.