开发者

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

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 =开发者_StackOverflow 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.


Read Scott Meyers Effective C++ to save yourself weeks of pain. This is the best $$ you will ever spend as a beginning C++ programmer. Especially, learn what RAII is.


When you declare a variable without allocation qualifiers, as you have, the compiler assumes you mean auto. An auto variable exists for the lifetime of the scope in which it is defined, and then goes away. This usually happens by (though not by fiat of the language itself) placing the storage location for those variables on the call stack. When the function completes, the memory used by those variables is reclaimed automatically when the call pops the stack frame for the function off the call stack.


The other answers are correct in that you won't have caused any memory leaks with this code. But for completeness, there are other ways to be wasteful with memory too. Like passing objects by value instead of by reference.

In your case here it's not a problem. You're passing doubles and booleans. On a typical machine, doubles are 8 bytes instead of the 4byte pointers required to pass by reference. Not too big of a deal unless you think this is going to be an extremely busy and concurrent function.

But if you were using larger objects (structures, classes, etc), you'd do well to pass const references instead of having the system create a new structure and invoke the copy constructor to populate it.


Your code is fine. Basic rule of C++ memory management is return what you got :). If you got some memory using new, return it back to the system with delete.

I understand where you are coming from. Here's my suggestion list to master memory management in C++:

  1. Learn to compare and contrast malloc/calloc/alloca/free with new/delete/new[]/delete[].
  2. Be confident about operator new/operator delete usage
  3. Understand placement new -- this in conjunction with 2 form the crux of user defined memory management.
  4. Google for the term RAII, learn about auto_ptr and scoped_ptr
  5. Learn to handle error conditions gracefully. For e.g. when new fails it's supposed to throw an exception of type std::bad_alloc.
  6. Look into Dougleas Lea's dlmalloc implementation (google it)

Also remember, for every new there must be a corresponding delete. Otherwise this is a case of memory "leak". Use prudence while calling new/delete -- too many of these calls will slow your program.

Finally, automatically managed programming languages including those that have garbage collection related API may not always be the best solution to your problem domain. Fine grained memory management does help in performance optimization if done properly.


You only need to destroy variables allocated in the heap (i.e. via either new or malloc call).

In your example you only have automatic variables so you can't destroy them manually.


Take a look at:

7.9 — The stack and the heap

This also might be helpful:

Memory Management Reference - Frequently Asked Questions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜