So far I have been writing programs in Java. So when I started C++, the first thing that came to my mind was how to destruct/delete/finalize objects I don’t need anymore.
With Java I used to set them to null so the garbage collector was taking care of it.
However, I don’t know how things worth with C++. I found this article http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B which solved most of my questions. But there are still a few things I didn’t understand.
1) In Java there is a way to force the garbage collector to clean right on the spot(which is not always useful, since it waits for a few trash to stack up before running). Is there a way to do that with C++?
2) (C++) Also the opposite of the above, how can i make it so that i put the object on a state of “marked to be deleted” and the programm decides when to clean it (like Java)?
3) (C++)Should i force the barbage collector to clean right on the spot(i am pretty sure that’s not the right way but i am asking just to be sure)?
I would appriciate it if you could give a small code example with which code triggers what.
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.
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
newkeyword), it must be destroyed and deallocated manually with thedeletekeyword. When you calldelete, 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:
and the
unique_ptris 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
Fthat represents that file, it might have a exclusive lock on that file. In C++, onceFis destroyed, you can immediately create an objectGthat uses that same file. In Java, there’s no guarantee that thefinalizerwill ever run, meaning that file may remain locked until your program ends. (Unlikely, but possible)