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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With