C++
  Home arrow C++ arrow Page 12 - A Simple Garbage Collector for C++
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

A Simple Garbage Collector for C++
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 48
    2005-06-21

    Table of Contents:
  • A Simple Garbage Collector for C++
  • Comparing the Two Approaches to Memory Management
  • Choosing a Garbage Collection Algorithm
  • What About auto_ptr?
  • An Overview of the Garbage Collector Classes
  • GCPtr In Detail
  • The Overloaded Assignment Operators
  • GCInfo
  • How to Use GCPtr
  • Allocating Arrays
  • A Larger Demonstration Program
  • Load Testing

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · Your copy constructor and assignment operator are much too complicated and add lots...
       · I just worked on implementing your GC and testing it out in some of my code. I...
       · one comment is clearly missing here: this is a great article.
       · Sir,The article is very informative.Thanks a lot.But there are instances when...
     

    Buy this book now. This article was excerpted from chapter two of The Art of C++, written by Herbert Schildt (McGraw-Hill/Osborne, 2004; ISBN: 0072255129). Check it out at your favorite bookstore today. Buy this book now.

    C++ ARTICLES

    - 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++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT