Is it possible to either create a coding standard or use of a library
that can be proved to eliminate any memory management errors in C++?
No.
But the same is true for Java. While Java does not technically allow memory leaks, it does have them (and other resource leaks) in practice if you do not pay attention.
A classical example, known particularly well in the Android world, is when a collection of listener instances keeps growing the longer a program runs, because listeners forget to unregister themselves. This can quickly cause hundreds of MBs leaking in a GUI application when the listener is an instance of some window or view class that keeps itself references to big graphics. Since all of that memory is still reachable, garbage collection cannot clean it up.
The fact that you have not technically lost the pointer (it's still in the collection) does not help you at all. Quite the contrary; it's the cause of the leak because it prevents garbage collection.
In the same vein as above, while Java does not technically allow dangling pointers, similar bugs can cause you to access a pointer to some window or view object which is still in a valid memory area for your program but which should no longer exist and is no longer visible. While the pointer access itself does not cause any crash or problem, other kinds of errors or crashes (like a NullPointerException
) usually follow soon enough because the program logic is messed up.
So much for the bad news.
The good news is that both languages allow you to reduce memory-management problems if you follow simple guidelines. As far as C++ is concerned, this means:
- Use standard collections (like
std::vector
or std::set
) whenever you can.
- Make dynamic allocation your second choice. The first choice should always be to create a local object.
- If you must use dynamic allocation, use
std::unique_ptr
.
- If all else fails, consider
std::shared_ptr
.
- Use a bare
new
only if you implement some low-level container class because the existing standard container classes (likestd::vector
or std::set
) do not work for your use case. This should be an extremely rare case, though.
There is also the Boehm garbage collector for C++, but I've never used it personally.