R
Ron James
C++ is a great language. You can instantiate an object on
the stack, grab whatever resources you need, and free them
in the destructor. Object destructors are called in the
correct order (the reverse order), and are guaranteed to
be called when the object goes out of scope.
Unfortunately this is not so in C# (or Java) since you
cannot tell when the Garbage Collector will run. In C#
you can call Dispose (assuming it's implemented), but you
you still might have several references to a invalid
object floating around. Alternatively you can take
advantage of the using statement IF the class implements
IDispose, however this can become unwieldy if you need
several nested using blocks.
So why did the developers of C# (and Java) not reference
count objects? Surely it would have been a simple matter
to implement reference counting, and guarantee calling the
destructor when the last reference to an object was set to
null. The GC could still run periodically to clean up and
re-organize memory, but at least the resource cleanup
problem would have been solved.
What am I missing?
Thanks.
the stack, grab whatever resources you need, and free them
in the destructor. Object destructors are called in the
correct order (the reverse order), and are guaranteed to
be called when the object goes out of scope.
Unfortunately this is not so in C# (or Java) since you
cannot tell when the Garbage Collector will run. In C#
you can call Dispose (assuming it's implemented), but you
you still might have several references to a invalid
object floating around. Alternatively you can take
advantage of the using statement IF the class implements
IDispose, however this can become unwieldy if you need
several nested using blocks.
So why did the developers of C# (and Java) not reference
count objects? Surely it would have been a simple matter
to implement reference counting, and guarantee calling the
destructor when the last reference to an object was set to
null. The GC could still run periodically to clean up and
re-organize memory, but at least the resource cleanup
problem would have been solved.
What am I missing?
Thanks.