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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.