Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this piece of C++ considered okay in terms of memory management?

Tags:

c++

I am kind of getting bogged down by the concept of memory management (all my previous programming languages doesn't need me to manage the memory). I'm not sure if creating a variable will consume memory if I don't destroy it later.

#include <math.h>
#include <iostream>
using namespace std;

double sumInfiniteSeries(double u1, double r){
 return u1 / (1 - r);
}

double sumInfiniteSeries(double u1, double r, bool printSteps){
 if (printSteps){
  double lastTotal;
  double total = 0.0;
  double sn = u1;
  for (int n=1;n<=1000;n++){
   lastTotal = total;
   total += sn;
   sn *= r;
   cout <<  "n = " << n << ": " << total << endl;
   if (fabs(lastTotal - total) < 0.000000000000001) return total;
  }
  return total;
 } else {
  return sumInfiniteSeries(u1, r);
 }
}

Do i need to "destroy" any variables in these 2 functions?

Edit: So when I create my own class and its instance would I need to start memory management?

like image 402
Pwnna Avatar asked Nov 29 '22 18:11

Pwnna


2 Answers

What memory management? You’re only using the stack here, no memory management needed.

Manual memory management comes into play when you fiddle with new and delete.

like image 128
Konrad Rudolph Avatar answered Dec 15 '22 22:12

Konrad Rudolph


As long as you stay away from new and especially delete, there is nothing to worry about w.r.t. memory management in C++.

If you do encounter a situation where you need to manually allocate some memory with new, the best thing you can do is to immediately hand the responsibility for that memory over to a smart pointer class, like auto_ptr<T>, unique_ptr<T>, shared_ptr<T>, etc.. Assuming you use the one with the right semantics, they will ensure the memory gets released at just the right time.

like image 40
Bart van Ingen Schenau Avatar answered Dec 16 '22 00:12

Bart van Ingen Schenau