JS Ext

Friday, January 18, 2013

Stack-based Garbage Collection

When comparing programming languages, a lot of people say that c++ does not have garbage collection.  While I understand why people say that, the statement isn't entirely true.  I'm not talking about Hans Boehm GC either.  Definitions are important to understand what I'm taking about.  Garbage collection is when the system automatically deletes unused memory for you.  Lets look at the following example:


int getLength( const char *str )
{
    std::string cppstr( str );
    return cppstr.length();
}


In this example, where does the delete of the string occur?  Why doesn't the developer have to delete the string?  I thought every object that gets created must be deleted?

This is an example of stack-based garbage collection.  In c++, you have the option to create objects in either the stack or the heap.  If you create an object in the heap, you have to delete that object.  If you create an object on the stack, you can NOT delete the object.  The system manages the deletion for you.  The object gets deleted when the stack frame is closed.  Stack objects has very limited usefulness.  That is why most objects are created on the heap.  It is still technically garbage collection, based on our definition above.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.