Development guide

Memory and Resources

Do not redefine the global new and delete operators.
When overloading the new operator for a class, always overload the delete operator too.
Do not use malloc(), realloc() or free().

In C++ data can be allocated statically, dynamically on the stack, or dynamically on the heap. There are three categories of static data: global data, global class data, and static data local to a function.

In C malloc(), realloc() and free() are used to allocate memory dynamically on the heap. This may lead to conflicts with the use of the new and delete operators in C++.

It is therefore forbidden to:

  1. invoke delete for a pointer obtained via malloc()/realloc(),
  2. invoke malloc()/realloc() for objects having constructors,
  3. invoke free() for anything allocated using new.

Moreover, avoid whenever possible the use of malloc(), realloc() and free().

Always use the array delete operator (delete []) when deallocating arrays.

If an array a having a type T is allocated, it is important to invoke delete in the correct way. Only writing delete a; will result in the destructor being invoked only for the first object of type T. By writing delete [] a; the destructor will be invoked for all objects that have been allocated earlier

Avoid global data if at all possible.

One difference between ANSI-C and C++ is in how constants are declared. If a variable is declared as a constant in ANSI-C, it has the storage class extern (global). In C++, however, it normally has the storage class static (local). The latter means that a new instance of the constant object is created each time a file includes the file which contains the declaration of the object, unless the variable is explicitly declared extern in the include file. An extern declaration in C++ does not mean that the variable is initialized; there must be a definition for this in a definition file. Static constants that are defined within a class are always external and must always be defined separately.

Do not allocate memory and expect that someone else will deallocate it later.

It may, at times, be tempting to allocate memory for an object using new, expecting someone else to deallocate the memory. For instance, a function can allocate memory for an object that is then returned to the user as the return value for the function. There is no guarantee that the user will remember to deallocate the memory and the interface with the function then becomes considerably more complex.

Always assign a new value to a pointer pointing to deallocated memory.

Pointers that point to deallocated memory should either be set to NULL (0) or be given a new value to prevent access to the released memory. Note that this can be a very difficult problem to solve when there are several pointers pointing to the same memory, since C++ has no garbage collection. It will avoid however the introduction of difficult to track bugs.