Thomas said:
In C++, the dynamic memory management is through
the "new" and "delete" operators or via the functions
"malloc" and "free". Don't mix the pairs.
Read the FAQs and Welcome.txt below for more information.
There is also book recommendations in there as well.
In particular, once you get the general idea of new and delete (or
malloc and free), you might want to have a look at so-called "Smart
Pointers". They are an idiomatic approach to memory management with C++,
and take a lot of the burden of managing memory in C++ (in particular,
this approach is essential in the presence of C++ exceptions).
Smart pointers solve the problem of memory leaks (i.e. allocating memory
(with "new") but not deallocating it (with "delete")) by encapsulating
the new and delete in their constructor and destructor, respectively.
The language guarantees that an object's destructor is always executed,
hence the delete is guaranteed to be executed.
The aforementioned FAQ (
http://www.parashift.com/c++-faq-lite) shows
such an approach in 16.21.
Other than that, these handle objects provide the same interface as
pointers (the dereference operator etc.), hence the name smart pointers.
Other keywords to google for in this regard are "handle-body idiom"
(e.g.
http://www.cs.vu.nl/~dejavu/context/node2.html) and "resource
acquisition is initialization" (RAII) (see part 8 of Stephen Dewhurst's
article "C++ Memory and Resource Management" at
http://www.informit.com/articles/article.asp?p=30642&seqNum=8), or just
"C++ memory management".
Kind regards,
Andreas