9 Answers
9

Yes, you have to delete every object created with newthat you own. In this very case it looks like class A owns that very instance of class B and is responsible for calling delete.

You'll be much better off using a smart pointer for managing class B instance lifetime. Also note that you have to either implement or prohibit assignment operator and copy constructor in class A to prevent shallow copying the object which will cause you much trouble.

As far as operating system deleting your memory.. yes, it will happen but only after the entire process terminates (i.e. your application exits). Only then all memory and other resources are reclaimed by the OS.

Thirdly, try to use new/delete only when necessary. In your scenario, you could just write

class A
{
B b;
A() {}
~A() {}
};

It would have the same effect and you avoid an extra dynamic memory allocation.

It's certainly necessary the way you've written it. Even with the delete, though, the class is fundamentally broken because it manages a resource but doesn't follow the rule of three.

That said, there's almost certainly no reason for manual memory management--there rarely is. It's likely that you should either just have a B object as a member variable, or you should be using a smart pointer, like QScopedPointer:

struct A
{
QScopedPointer<B> b;
A() : b(new B()) { }
// No ~A() needed; when the A object is destroyed, QScopedPointer ensures
// that the B object pointed to by the member 'b' is destroyed and deleted.
};

Resource management is more than just deallocating memory. Yes, most platforms will make any memory you allocate when the process ends, and memory is cheap enough that maybe you won't notice for a while. But what about the file b is holding open, or the mutex it will unlock in its destructor? Well before you run out of memory, you can encounter issues from letting your objects live past their usefullness.

Anything that you allocate with new you should free with delete, otherwise there is a memory leak in your application.

On most modern operating systems (certainly the OSes that people usually run on desktop computers) anything that a process uses will be cleaned up when the process ends, so if you forget a delete, then the memory will be freed anyway. But you should rely on this.

Long ago I programmed on the Amiga in C. Its operating system was much less sophisticated than today's operating systems. If you'd allocate memory and not free it, it would stay allocated until you switched off or rebooted the computer, even after the process had ended. Memory leaks were an even more serious problem then.