I use to program mainly with C/C++, that’s make me dealing with pointers and memory management daily. This days I’m trying to develop using other tools, such as Java, Python and Ruby.
The problem is that I keep thinking C++ style, I’m writing code as C++ usually written in almost every programming language, and the biggest problem is the memory management, I keep writing bad code using references in Java and just get as close as I can to the C++ style.
So I need 2 thinks here, one is to trust the garbage collector, let’s say by seeing benchmarks and proofs that it’s realy working in Java, and know what I should never do in order to get my code the best way it can be.
And the second think is knowing how to write other languages code. I mean I know what to do, I’m just never write the code as most Java or Python programmers usually do, are there any books for C++ programmers just to introduce me to the writing conventions?
(by the way, forgive me for my English mistakes)
One difference to bear in mind is that in C++ the destructor can be used to clean up any kind of resource, not just memory (i.e. RAII). In Java you have to explicitly close files, sockets, datastore connections etc in a try – finally block. If you put resource cleanup code in a Java finalize method then it may get called at some indeterminate time in the future, or never, so is not recommended. So in some ways this puts a bigger burden on the programmer, not less.
Python is somewhere in between – you can use the ‘with’ statement to handle automatic cleanup for most resources.
The two problems in C++ memory management are memory leaks and trying to use an object that has already been destroyed. As others have pointed out you can also get memory leaks in Java (and Python) if you keep a reference to an object that you no longer need, which in turn may have references to other objects. Memory leaks in Java may be less frequent but when they do occur they can be much bigger than in C++. Judicious use of weak references can help, as well as assigning null to variables that are no longer needed. However this leads to the second problem – if you then try to use the variable you will get a NullPointerException. This is more helpful than the segmentation fault you would probably get in C++, but is still an issue.
So all the things you learnt about memory management in C++ still apply in Java, but you have to do it for other resources too.