C++ is very different than Java in this area, so here's a brief overview:
allocation: memory is set aside for an object.
construction: The object is prepared to be used.
destruction: The object "finishes" everything and disassembles itself.
deallocation: the memory is given back to the system.
int main() {
int myint; //automatic int object is allocated and constructed
//stuff
} // when main ends, automatic int object is destroyed and deallocated
int main() {
int* mypointer; //automatic pointer object is allocated and constructed
mypointer = new int; //dynamic int object is allocated and constructed
//stuff
delete mypointer; //dynamic int object is destroyed and deallocated
} // when main ends, automatic pointer object is destroyed and deallocated
// note: Pointers to _not_ delete the object they point to.
class myclass {
//members
public:
myclass() {} //this is the default constructor
myclass(const myclass& rhs) {} //this is the copy constructor
myclass& operator=(const myclass& rhs) {return *this} //this is the assignment operator
~myclass() {} //this is the destructor
};
When a function ends, all the variables in the function itself (which we call automatic) have their destructors called, and then they are deallocated automatically. This means for objects local to a function, they automatically clean themselves the instant the function ends. This also applies magically to members of a class. When it is destroyed, each of it's members will automatically be destroyed. This means most destructors are empty.
If you allocate stuff manually (with the new
keyword), it must be destroyed and deallocated manually with the delete
keyword. When you call delete
, it will destroy (and deallocate) right there and then, and won't continue until it is done. If you forget, it WILL NOT EVER GET DEALLOCATED (altough, some operating systems will deallocate it when your program ends).
Since people make mistakes, the "correct" thing to do when you need dynamic objects is:
int main() {
std::unique_ptr<myclass> myptr = new myclass(); //allocate and construct
} //both the unique_ptr and the dynamic object are destroyed and deallocated
and the unique_ptr
is smart enough to automatically clean up the thing it points at, freeing you for bigger concerns.
The reason C++ does this is because if you have a object F
that represents that file, it might have a exclusive lock on that file. In C++, once F
is destroyed, you can immediately create an object G
that uses that same file. In Java, there's no guarantee that the finalizer
will ever run, meaning that file may remain locked until your program ends. (Unlikely, but possible)