All objects allocated with new
must have a corresponding delete
to avoid leaking. The same is true with new[]
and delete[]
(these happen to be separate operators, BTW).
As J.N. pointed out, in the code example above, you might as well use the stack and avoid operator new/delete. If the use of the stream is limited to some well-defined scope, there's no need to create your object on the free store (heap).
What you actually don't need here is the call to close
. File streams already close when they are destroyed (in the destuctor) so it's fine to omit it. In fact, that's one of the big advantages of using file stream objects over fopen/fclose as we can see here: Do I need to manually close an ifstream?
Furthermore, if you use C++ the way Stroustrup encourages with strong conformance to his RAII idiom, you generally want to avoid writing code that needs to manually call delete all together. This might be a bit over your head at the moment, but we have smart pointers available in C++11 like shared_ptr
and unique_ptr
which will automatically destroy objects for us:
shared_ptr<ofstream> output_stream(new ofstream(...));
// ^^ This will not leak and the file will gracefully close
// when 'output_stream' is destroyed. It makes the need to
// call both delete and close unnecessary.
If you venture into the realm of C++ exception handling, you'll find this use of the destructor to clean up resources for you automatically is not only convenient but quite essential to coding safely and correctly.