Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
Haves and havenots
Regularly, I see discussions about why a C++ programmer should or should not nullify a pointer to an object after deleting the object pointed to.
This leads to a couple of thoughts.
Basically, you should treat a dynamically allocated object as a resource.
This means that only one pointer that points to it is the owner of the resource.
This rule holds not only for pointers, but for every resource you acquire, use and subsequently release.
The next brainwave is that you need to wrap resources in a wrapper class.
This is a pattern you will frequently encounter in a number of libraries, for example the VCL.
This framework consists at least in parts of classes that are wrapped around resources, be it windows, registry keys or files.
Pointers
Having read the above, pointers can be divided into two types.
The two types are 'owning pointers' and 'alias pointers'.
Owning pointers are the pointer variables of which we say that they own the object pointed to.
Alias pointers are the pointer variables that just reference the objects pointed to.
The rule here is that only owning pointers may be used to delete the object that they point to, while alias pointers may not:
SomeType* owner = new SomeType; SomeType* alias = owner; ... delete owner; owner = 0; alias = 0;From this piece of code it must be obvious that it is quite a hassle to keep owning pointers and alias pointers apart. There are at least a couple of tricks to keep them apart, and again, this is a question of wrapping the object pointed to in a class.
auto_ptr
The STL has a template class called auto_ptr.
Objects of this class are wrappers around a pointer with the property that they will delete the object pointed to once the auto_ptr object goes out of scope or you assign a different pointer to it.
There are members to refer to the pointer and the object pointer to and to make the auto_ptr object give up its ownership.
Envelope-letter class and counted-pointer class
James Coplien describes two ways to wrap up resources in such a way that they are not released until the last reference to the resource goes out of scope.
Please look up envelope-letter class and counted-pointer class in Advanced C++ Programming Styles and Idioms.