Construction and Destructions of Objects
Destroying objects explicitly
The reverse operations of the
new operator are destroying an object and returning the object’s memory back to the
GC. Normally, these operations are executed automatically at unspecified times.
However, sometimes it is necessary to execute destructors at specific points in the program. For example, an object may be closing a
File member in its destructor and the destructor may have to be executed immediately when the lifetime of the object ends.
destroy() calls the destructor of an object:
After executing the destructor,
destroy() sets the variable to its
.init state. Note that the
.init state of a class variable is
null; so, a class variable cannot be used once destroyed.
destroy() merely executes the destructor. When to reuse the piece of memory that used to be occupied by the destroyed object is still up to the
Warning: When used with a struct pointer,
destroy()must receive the pointee, not the pointer. Otherwise, the pointer would be set to
null, but the object would not be destroyed: