Search code examples
c++dynamicreturnmemberdelete-operator

Heap and delete in function calls. How do I delete local dynamic memory?


I know memory that has been dynamically allocated and using the heap needs to be manually deleted using delete. Is this also the case if a dynamic object is created in a class function that will go out of scope? Here is a snippet.

    Fraction* Fraction::add(const Fraction* fr) const{ 
      int gcd;
      Fraction* temp;

      gcd = gcdRecur(num * fr->denom + fr->num * denom, 
                     denom * fr->denom);

      temp = new Fraction((num * fr->denom + fr->num * denom) / gcd, 
                          (denom * fr->denom) / gcd);

      return temp;
   }

In this case, temp is a pointer to a dynamic object of type Fraction using 'new' (right?). If I am returning this pointer to wherever the class function 'add' was called, will I need to delete the local pointer 'temp'? If so, how can I accomplish this?

EDIT: My (wrong) interpretation of using new in this class member is because the Fraction objects are being instantiated through pointers to Fractions (like so):

    int main() {
      menu()
      return 0;
    }

    void menu() {
      Fraction* fr1 = 0;
      Fraction* fr2 = 0;
      Fraction* fr3 = 0;
      // ... user chooses to initialize, so fr1, fr2, fr3 no longer null

      // ... user chooses to add. call submenu, pass fr1, fr2, fr3 by POINTERS?
      addMenu(fr1, fr2, &fr3);
    }

Looks bad... Here's the header for the addMenu:

     void addMenu(const FractionTeddyD*, const FractionTeddyD*, FractionTeddyD**);

EDIT #2: Solved without using 'new'. T


Solution

  • It does indeed need to be deleted, otherwise the memory will be leaked. You can't delete it locally, since the caller needs to use it after the function returns. The caller will have to delete it once it's no longer needed. Obviously, this is error-prone, which is why you should always use RAII to manage dynamic resources.

    In this case, you should change the return type to a smart pointer like std::unique_ptr<Fraction>.

    On the other hand, why are you using new here at all? Returning a value would be simpler and almost certainly faster.