Home arrow C++ arrow Page 12 - A Simple Garbage Collector for C++
C++

A Simple Garbage Collector for C++


The use of dynamically allocated memory must be managed, because it has a tremendous effect on the performance of your programs. The current trend in handling dynamic memory seems to be shifting toward an automated approach. While C++ uses the manual approach for managing dynamic memory, this does not mean that it can't be automated in that language -- thus giving the C++ programmer the best of both worlds. This article explains how to do it. It is excerpted from chapter two of The Art of C++, written by Herbert Schildt (McGraw-Hill/Osborne, 2004; ISBN: 0072255129).

Author Info:
By: McGraw-Hill/Osborne
Rating: 4 stars4 stars4 stars4 stars4 stars / 73
June 21, 2005
TABLE OF CONTENTS:
  1. · A Simple Garbage Collector for C++
  2. · Comparing the Two Approaches to Memory Management
  3. · Choosing a Garbage Collection Algorithm
  4. · What About auto_ptr?
  5. · An Overview of the Garbage Collector Classes
  6. · GCPtr In Detail
  7. · The Overloaded Assignment Operators
  8. · GCInfo
  9. · How to Use GCPtr
  10. · Allocating Arrays
  11. · A Larger Demonstration Program
  12. · Load Testing

print this article
SEARCH DEVARTICLES

A Simple Garbage Collector for C++ - Load Testing
(Page 12 of 12 )

The following program load tests GCPtr by repeatedly allocating and discarding objects until free memory is exhausted. When this occurs, a bad_alloc exception is thrown by new. Inside the exception handler, collect( ) is explicitly called to reclaim the unused memory, and the process continues. You can use this same technique in your own programs.

// Load test GCPtr by creating and discarding
// thousands of objects.
#include <iostream>
#include <new>
#include <limits>
#include "gc.h"
using namespace std;
// A simple class for load testing GCPtr.
class LoadTest {
 
int a, b;
public:
 
double n[100000]; // just to take up memory
 
double val;
 
LoadTest() { a = b = 0; }
 
LoadTest(int x, int y) {
    a = x;
    b = y;
    val = 0.0;
 
}
  friend ostream &operator<<(ostream &strm, LoadTest &obj);
};
// Create an inserter for LoadTest.
ostream &operator<<(ostream &strm, LoadTest &obj) {
  strm << "(" << obj.a << " " << obj.b << ")";
  return strm;
}
int main() {
  GCPtr<LoadTest> mp;
  int i;
 
for(i = 1; i < 20000; i++) {
    try {
      mp = new LoadTest(i, i);
   
} catch(bad_alloc xa) {
      // When an allocation error occurs, recycle
      // garbage by calling collect().
      cout << "Last object: " << *mp << endl;
      cout << "Length of gclist before calling collect(): "
           << mp.gclistSize() << endl; 
      GCPtr<LoadTest>::collect();
      cout << "Length after calling collect(): "
          
<< mp.gclistSize() << endl;
    }
  }
 
return 0;
}

A portion of the output from the program (with the display option off) is shown here. Of course, the precise output you see may differ because of the amount of memory available in your system and the compiler that you are using.

Last object: (518 518)
Length of gclist before calling collect(): 518
Length after calling collect(): 1
Last object: (1036 1036)
Length of gclist before calling collect(): 518
Length after calling collect(): 1
Last object: (1554 1554)
Length of gclist before calling collect(): 518
Length after calling collect(): 1
Last object: (2072 2072)
Length of gclist before calling collect(): 518
Length after calling collect(): 1
Last object: (2590 2590)
Length of gclist before calling collect(): 518
Length after calling collect(): 1
Last object: (3108 3108)
Length of gclist before calling collect(): 518
Length after calling collect(): 1
Last object: (3626 3626)
Length of gclist before calling collect(): 518
Length after calling collect(): 1

Some Restrictions

There are a few restrictions to using GCPtr:

  1. You cannot create global GCPtrs. Recall that a global object goes out of scope after the rest of the program ends. When a global GCPtr goes out of scope, the GCPtr destructor calls collect( ) to try to release the unused memory. The trouble is that, depending on how your C++ compiler is implemented, gclist may have already been destroyed. In this case, executing collect( ) will cause a runtime error. Therefore, GCPtr should be used only when creating local objects.

  2. When using dynamically allocated arrays, you must specify the size of the array when you declare a GCPtr that will point to it. There is no mechanism that enforces this, however, so be careful.

  3. You must not attempt to release the memory pointed to by a GCPtr by explicitly using delete. If you need to immediately release an object, call collect( ).

  4. A GCPtr object must point only to memory that is dynamically allocated via new. Assigning to a GCPtr object a pointer to any other memory will cause an error when the GCPtr object goes out of scope because an attempt will be made to free memory that was never allocated.

  5. It is best to avoid circular pointer references for reasons described earlier in this chapter. Although all allocated memory is eventually released, objects containing circular references remain allocated until the program ends, rather than being released when they are no longer used by another program element.

Some Things to Try

It is easy to tailor GCPtr to the needs of your applications. As explained earlier, one of the changes that you might want to try is collecting garbage only after some metric has been reached, such as gclist reaching a certain size, or after a certain number of GCPtrs have gone out of scope.

An interesting enhancement to GCPtr is to overload new so that it automatically collects garbage when an allocation failure occurs. It is also possible to bypass the use of new when allocating memory for a GCPtr and use factory functions defined by GCPtr instead. Doing this lets you carefully control the dynamic allocation of memory, but it makes the allocation process fundamentally different than it is for C++ís built-in approach.

You might want to experiment with other solutions to the circular reference problem. One way is to implement the concept of a weak reference, which does not prevent garbage collection from occurring. You would then use a weak reference whenever a circular reference was needed.

Perhaps the most interesting variation on GCPtr is found in Chapter 3. There, a multithreaded version is created in which garbage collection takes place automatically, when free CPU time exists.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials