Part of the standard C++ library is based on the STL library
developed by SGI. All good compilers should provide this
library. Get comfortable with the features it provides. Learn to
use the standard C++ include files and the std
namespace. The Standard Template
Library Programmer's Guide from SGI is a good place to look
for documentation. Most of it applies for the standard C++ library
even though the document is written for STL.
For the most part, try to avoid code like this:
... MyType* myObject = new MyType(); MyType* myArray = new MyType[10]: ... delete[] myArray; delete myObject; ...
If an exception is thrown or control flow is otherwise
interrupted between the new
and delete
statements, memory will be leaked. The code can be made safe using
a try-catch block that performs the delete operations before
rethrowing the exception.
The better and more general solution is to use datatypes that, unlike pointers, ensures that the memory is freed.
... // Stack allocation MyType myObject(); MyType myArray[10]; ... /* Will automatically be deallocated when variables go out of scope. */ ...
or
#include <memory> #include <vector> ... using namespace std; ... // Heap allocation auto_ptr<MyType> myObject(new myObject()); vector<MyType> myVector(10); ... /* Deconstructors of these types will automatically free the dynamically allocated memory when variables go out of scope. */ ...
The two examples above perform safe memory allocation, and will not leak memory, regardless of whether an exception is thrown, or control flow is interrupted in some other way.