Sunday 3 February 2013


Automatic Garbage Collection in C/C :

False. C and C don't mandate automatic garbage collection, but it's available anyway (e.g., see the Boehm/Demers/Weiser collector).
In C/C we have to manually remove the Object address inside the for loop.
Again, false. In C or C , we'd define the object using the automatic storage class, which would deterministically destroy the object:

for ( int i = 0 ; i < 100 ; i ) { Object o ; }

Just for example, let's do a quick test, by defining Object something like this:

struct Object {
Object () { 
std :: cout << "Created an Object\n" ; 
}
~ Object () {
std :: cout << "Destroyed an Object\n" ; 
} 
};

For the loop above, this generates:

Created an Object Destroyed an Object Created an Object Destroyed an Object Created an Object Destroyed an Object
[97 more repetitions of the same pattern removed ]
Do we have to reboot each time as well to properly remove the Object reference in C ?
No, of course not. The fundamental difference between C and Java in this respect is that in C the object destruction isdeterministic, but in Java it's not. Just for example, in C , the code above must follow exactly the prescribed pattern -- the body of the loop is a block, and the object must be created on entry to the block, and destroyed on exit from the block. In Java, you get no such assurance. It might only destroy the firstobject after it has allocated 10 or 20. The objects may be destroyed in any order, and there's not really a guarantee that any particular object will be destroyed at all.

That difference isn't always important, but certainly can be. In C , it's used to support
RAII (aka., SBRM -- stack bound resource management). This used to assure not only that memory is freed when no longer needed(i.e., the same thing Java's automatic garbagecollector handles) but also that other resources (anything from files to widgets to network or database connections) are handled automatically as well. And advantage of RAII is that finally-blocks are rarely necessary in C : local variables that reference to a resource that should be freed immediately are usually allocated on the stack, and therefore get released automatically. No need for finally blocks here.

1 comment:

  1. Because, when using the power of C++, thereis no need.

    Herb Sutter: " I've haven't written delete in years. "

    ReplyDelete