|
| |
In C++, objects are destroyed
using class destructors
- If a C++ object has been allocated using the new operator, it is the programmer's responsibility
to remember to clean it up, using the delete operator.
(In C++, you can allocate objects on the run-time stack, or in static
space, in addition to from the heap.)
- Memory allocation is a very error-prone
business in C and C++ -- memory leaks are a constant
source of problems, and are very hard to find and fix.
In Java, objects are destroyed
automatically using a process called garbage collection
- There is no delete operator, as in C++.
- There is no free function or method, as in C.
- The Java garbage collector runs in a
low-priority thread, so garbage collection takes place when
nothing else is happening.
In Java, an object becomes
available for garbage collection when the number of references to
that object drops to zero.
For example:
{
Car[] carArray = new Car[10];
for (int i = 0; i < 10; i++)
carArray[i] = new Car();
process(carArray);
// Do more stuff
// carArray, etc., becomes eligible
// for garbage collection when it goes out of scope
}
|
Or, you can give the garbage collector a chance to get rid of an instance
earlier, if you know you won't need the instance again:
{
Car[] carArray = new Car[10];
for (int i = 0; i < 10; i++)
carArray[i] = new Car();
process(carArray);
// Don't need carArray any more
carArray = null; // eligible for garbage
// collection here
// Do more stuff
}
|
You can even 'suggest' that
garbage collection be done:
System.gc();
In Java, unlike in C++, there are
no class destructors. You don't need them in Java, since
allocated memory is cleaned up for you by the garbage
collector. (There are situations when you can still get memory leaks,
but it's much less of a problem than in C/C++, and Java's solution is different
-- there are no destructors in Java.)
|