TweetFollow Us on Twitter

Deferred Garbage Collection

Volume Number: 13 (1997)
Issue Number: 12
Column Tag: C++ Workshop

Deferred Garbage Collection

by Marc White

Implementing a simple deferred C++ object garbage collection class

Self Deleting Objects

When developing object oriented software using C++ there are certain situations where you may need an object that can delete itself. For instance, you might have a window or dialog class that manages its own mouse clicks and key down events. But what does the dialog object do when it determines that the user has pressed the escape or delete key, or clicked the window's close box? To stay true to the object oriented design, the window should be able to do whatever processing is needed when it determines that it is being closed and then free up the memory allocated for the object by itself.

Delete This

While the C++ syntax delete this is a legal call, it can cause serious problems if the object that makes the call is referenced in any way after the call is made. This could possibly happen while the stack is unwinding after a mouse click or key down event.

The TGarbageCollector Class

The TGarbageCollector class is a simple, drop in utility class that allows any C++ object to be safely deleted at a later time.

Listing 1: The TGarbageCollector Class

The TGarbageCollector class is a non-instance class with two public static methods: Add, and Empty, and one private static member variable: fTrashCan which is pointer to a TGarbage object.

class TGarbageCollector {
friend class TGarbage;
public:
  static void Add      ( void *trash );
  static void Empty    ( void );
  
private:
  static TGarbage      *fTrashCan;
};

TGarbageCollector::Add

The Add method of the TGarbageCollector class simply instantiates a new TGarbage object passing it a pointer to the C++ object to be deleted. Note that the trash pointer is a void pointer.

void TGarbageCollector::Add( void *trash )
{
  // create a new TGarbage object
  new TGarbage( trash );
}

TGarbageCollector::Empty

The Empty method of the TGarbageCollector class deletes all of the TGarbage objects pointed to by the fTrashCan variable. This method should be called periodically at idle time in the application's main event loop. The TGarbage object's destructor maintains the linked list.

void TGarbageCollector::Empty( void )
{
  // delete all of the items in the trash can
  while( TGarbageCollector::fTrashCan )
    delete( TGarbageCollector::fTrashCan );
}

I developed the TGarbageCollector class as a part of an application framework I was designing. The easiest way to design the garbage collection class would have been to have it delete only objects derived from a specific class, perhaps a TTrashableObject class. But, I wanted the garbage collector to be able to delete any C++ object, and I didn't want to have every class in the framework be derived from a single base class.

The TGarbage Class

This is where the TGarbage class comes in. Because the TGarbage class accepts a void pointer as a pointer to the object it will delete, any pointer can be passed into the garbage collection class to be deleted. This means that it is up to the developer (not the compiler) to make sure that the pointer passed in is a pointer to a valid C++ object.

There is one more catch which I will describe in the What's the Catch section, but for now let's take a look at the TGarbage class.

Listing 2: The TGarbage Class

The TGarbage class is a simple self-linking singly linked list class which accepts a void pointer through its constructor. It stores a pointer to the object to delete in the fTrash variable and a pointer to the next TGarbage object in the list in its fNext variable.

class TGarbage {
public:
            TGarbage    ( void *trash );
  virtual    ~TGarbage  ( void );
private:
  void        *fTrash;
  TGarbage    *fNext;
};

TGarbage::TGarbage

The TGarbage constructor stores a pointer to object to delete in its fTrash variable. Next it links itself into the linked list pointed to by the TGarbageCollector's static fTrashCan variable. It can access this private item since the TGarbageCollector has the declared the TGarbage class as a friend.

TGarbage::TGarbage( void *trash ) : fTrash( trash )
{
  // store a pointer to the next item in the chain
  if( TGarbageCollector::fTrashCan )
    this->fNext = TGarbageCollector::fTrashCan;
  else
    this->fNext = nil;
  
  // set this item as the first item in the trash can
  TGarbageCollector::fTrashCan = this;
}

TGarbage::~TGarbage

This is where the real magic happens. When the TGarbage object gets deleted we have no idea what type of object its fTrash variable points to, all that we know is that it is pointing to a C++ object. So just type cast it to a C++ class pointer (in this case a TGarbage pointer) and call the delete operator. The real object's destructor will get called and its memory will be deallocated. It's just that easy!

TGarbage::~TGarbage( void )
{
  // pull this object out of the linked list
  TGarbageCollector::fTrashCan = this->fNext;
  
  // delete the trash
  delete( (TGarbage *)this->fTrash );
}

Sample Usage

Let's take a look at the TGarbageCollector class in action. Code listing 3 shows the DoKeyDown method of a typical dialog class.

Listing 3: A Dialog Class Method

void FDialog::DoKeyDown( char theKey )
{
  switch( theKey ) {
    case kEscKey:
      // add this object to the trash
      TGarbageCollector::Add( this );
      // hide this dialog
      this->Hide();
      // do any other processing needed here before closing
      break;
    default:
      inherited::DoKeyDown( theKey );
  }
}

Notice that the dialog can add itself to the trash at any time once it determines that it needs to be deleted. The dialog object is still valid until the trash gets collected.

Next we'll take a look at the event loop method of a typical application class. This is where the TGarbageCollector's Empty method gets called and all of the objects added to the trash are deleted.

Listing 4: An Application Class Event Loop Method

void FApplication::EventLoop( void )
{
  EventRecord  theEvent;

  while( this->fQuit == false ) {
    if( WaitNextEvent( everyEvent, &theEvent, 30, nil ) ) {
      switch( theEvent.what ) {
        // handle all normal events here
        default:
          TGarbageCollector::Empty();
          break;
      }
    } else {
      TGarbageCollector::Empty();
    }
  }
}

What's The Catch?

So there has to be a catch, right? Well, of course there is. The catch is that any C++ object added to the trash must be structured in the same way as the object used to type cast the void pointer in the TGarbage object before calling its delete operator.

In simpler terms, any object added to the trash must have a virtual destructor, and its destructor must be the first virtual method of that class. This is because of the way a C++ object is structured from a class.

The TGarbage class typecasts the void pointer to the object it is going to delete into a pointer to a TGarbage object. This instructs the compiler to use the virtual table, or vtbl, of the TGarbage class to find the location of the object's destructor which it calls before deallocating the object's memory.

In the case of the TGarbage class, the destructor is the first virtual method of the class and therefore will be the first entry in the vtbl. As long as any object added to the trash can has its destructor as the first item in the vtbl, it will be properly called when the TGarbage class deletes the object.

What would happen if the object being trashed did not have a virtual destructor, or if the destructor was not the first virtual method? If the object's virtual destructor is not the first virtual method in the class, or it's destructor is not virtual, then before the memory for that object is deallocated the first virtual method of that class will be called. In the case of an object that does not have any virtual methods, the object will not even have a vtbl which means that some random memory location is going be executed as a method. Obviously, neither of these two scenarios are desirable, which is why it is very important that the developer structures the classes for trashable objects properly.

Multiple Inheritance

Can objects that use multiple inheritance be successfully deleted using the TGarbageCollector class? In short, yes, as long as they still adhere to the virtual-destructor-first method like the other classes.

However, there is an exception. Depending upon how the compiler implements multiple inheritance (I am using CodeWarrior for this example), as long as the first class specified in the inheritance chain has a virtual destructor as its first virtual method, the order of the virtual methods of the other superclasses does not matter.

Listing 5: Multiple Inheritance

// destructor is the first virtual method
class A {
public:
              A    ( void );
  virtual      ~A    ( void );
};

// destructor is the second virtual method
class B {
public:
              B    ( void );
  virtual void  Test  ( void );
  virtual      ~B    ( void );
};

// inherit from A first, then B
class C : public A, public B {
public:
              C    ( void );
  virtual      ~C    ( void );
};

// inherit from B first, then A 
class D : public B, public A {
public:
              D    ( void );
  virtual      ~D    ( void );
};

In code listing 5, class A follows the virtual-destructor-first method which would allow any object of class A to be deleted properly by the TGarbageCollector class. Class B, however, has its virtual destructor declared as the second virtual method in the class, and therefore, would not be deleted properly by the TGarbageCollector class. The B object's Test method would actually get called when the TGarbage class deleted it.

Since class C inherits from class A first and class B second, class C objects can successfully be deleted using this method. When the TGarbage class calls the C object's delete operator, the class C destructor will be called first, the class B destructor second, and the A destructor third.

Class D, however, inherits from the B class first, which means that it will behave exactly like a B object would when being deleted by the TGarbageCollector, the inherited B object's Test method will get called.

So, even though there is an exception to the virtual-destructor-first rule in the case of multiple inheritance, it is much safer to make sure that any object that might be deleted by the TGarbageCollector have its virtual destructor declared before any other virtual methods.

Summary

The TGarbageCollector class provides a simple means of adding deferred object deletion to any C++ application. However, the developer must make certain that the classes of objects which will be deleted in this manner are structured according to the virtual-destructor-first rule.


Marc White is a Macintosh programmer at US WEST Dex, Inc., where he develops client/server software used to paginate the US WEST phone directories. He can be reached at mwhite@eagle.mrg.uswest.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.