What do I have to garbage collect in a C++ destructor-Collection of common programming errors
You must delete
every pointer you allocate with new
. It’s that simple, and it’s that complicated; you must not lose track of any pointer allocated by new
until you have delete
d it.
Also, you need to make sure that if you use new[]
to allocate a pointer, you call delete[]
to deallocate it.
It’s not about what pointers you happen to have in a class instance. You need to know who owns them (the owner is the one responsible for deleting them). If your object owns those pointers, then it should delete them. If it doesn’t own them, then it shouldn’t.
This is also why experienced C++ programmers avoid naked pointers where possible. Smart pointers allow you to express ownership types semantically in the language. That way, you don’t have to keep track of who owns what; you know who owns it by the type of smart pointer being used.