delete NULL
Ξ August 19th, 2009 | → 0 Comments |
∇ Programming | ∇ C++, delete, free, null, Tip |
This is one of many small reason which makes me prefer C++ to C.
Of course, object programming provide much better encapsulation and abstraction mechanisms than structs and ’simple’ functions or procedures, but today’s tip is not about that. It’s about managing of dynamically allocated memory.
C provides memory block management with functions from the malloc family to allocate memory chunks (for raw management by the programmer) and the infamous free function to release previously allocated memory, while C++ provides a cleaner (at least in my opinion) approach. C++ defines two ’special’ operators:
- operator new allocates a new chunk of memory, which allocated memory with a given initialization behaviour encapsulated in an object. Also, the access to the allocated memory is clear and well defined by the class interface.
- and operator delete to release previously allocated memory.
But why all this talk? Because I learned a new thing this week (or at least it became more present in my mind). In both languages, you can call the release mechanisms (free or delete) using a NULL pointer without having to protect against undefined behaviour. This means that both of the following are correct:
double *p = 0x0
free( p );
double *q = 0x0;
delete q;
This feature can be used in C++ to provide the following class scheme:
class Base;
class Derived: public Base;
class Actual { private: Base *ptr; public: Actual(): ptr(NULL) {} Actual(Base *ptr): ptr(ptr) {} virtual ~Actual() { delete ptr; } };
class FirstActual: public Actual {
public:
FirstActual(): Actual() {}
virtual ~FirstActual() {}
};
class SecondActual: public Actual {
public:
SecondActual(): Actual( new Derived() ) {}
virtual ~SecondActual() {}
};
By observing in detail the example, it’s easy to understand how class Actual stores objects of class Base or any of their derived types, even if the object pointed by ptr is allocated (which is not mandatory) by the classes derived from Actual. For instance, FirstActual doesn’t allocate a new object which means that ptr remains NULL. SecondActual creates a new instance of a Derived object, passes it to the Actual class, and after that no more memory management worries are necessary. The implementation of the class Actual shall be responsible by calling the associated delete (in the case the delete of a Derived object).



