Sessions on advanced C++ programming
Half-day seminar at CCC
Author: Zoltán Porkoláb
Budapest, 2007
A.4. Advanced memory handling
Topics
- Storage types in C++
In C++ objects are mapped into the memory based on their
storage types. Different storage types means
different life rules.
- The new and delete operators
New and delete expressions are calling new and
delete operators. These functions form a complex
set of operators.
- Overloading new and delete
New and delete operators could be overloaded at two levels:
as class member, we can define the allocation and
deallocation process for objects for a certain class. At
global level, we define these operations for all
dynamic storage objects.
- Extra parameters for new and delete
As we can overload new and delete operators at class or global
level: we can provide extra parameters, for debug or other
purposes. This example explain the details.
- Handling exceptions thrown by constructor
When a constructor throw an exception under creation of object
in the free space, the new expression catch this, and
calls the according delete operator. In this example You can
study this scenario.
- Resource allocation problems
Memory leaks and other resource deallocation problems could be
a major problem when exceptions are used in a C++ program. We
see some typical dangerous situation and solution. Stroustrup
suggested Resource allocation is initialisation strategy
as the solution.
- The auto_ptr class
This class is a wrapper for memory resource
handling. Auto_ptr is the only smart pointer class in the
C++ standard library and widely used in programs.
- Problems with auto_ptr
The auto_ptr are not "silver bullets" for resource management.
There are situations, when careless use of auto_ptr can cause
memory leaks.
- Arrays are not polymorphic
In object oriented programming, pointers to base could refer to
derived objects. However arrays are very special in this case:
arrays are not plymorphic.
- Array delete adapter
The purpose of this code is to solve the array-problem of
auto_ptr class. Arrays are not valid constructor parameters
for auto_ptr, because auto_ptr destructor always calls delete,
rather than delete[].
- Shared_ptr
The shared_ptr and shared_arr classes are
part of the tr1 library; the next extension of the
C++ language.
- Example smart pointer
This value_ptr class solves a special problem: when
aggregation is implemented via pointers, special care must be
taken on object ownership.