Game Development Reference
In-Depth Information
An allocated object of SomeClass is assigned to the smart pointer Ptr . At the end of
Test() , the smart pointer is automatically destroyed, and the number of references to the
allocated object becomes zero. As such, the allocated object is destroyed implicitly with the
delete() call, thereby avoiding memory leaks.
There's more...
We extensively check our smart pointers to be non-null and we want to use the traditional
syntax like the following:
if ( SomeSmartPointer ) ...
This can be achieved without adding a conversion operator to another usable type. The
following is how it is done using a private inner class:
private:
class clProtector
{
private:
void operator delete( void* );
};
public:
inline operator clProtector* () const
{
if ( !FObject ) return NULL;
static clProtector Protector;
return &Protector;
}
Basically, the condition if ( SomeSmartPointer ) will cast a smart pointer to a pointer
to the clProtector class. However, the C++ compiler will prevent you from misusing it.
The operator delete( void* ) operator of clProtector should be declared but not
deined, preventing the user from creating the instances of clProtector .
One common problem with smart pointers is the cyclic reference problem. When an object A
holds a reference to an object B , and at the same time the object B holds a reference to the
object A , the reference counter of both objects cannot be zero. This situation is quite common
for the container classes and can be avoided by using a raw pointer to the containing object,
not a smart pointer. See the following code as an example:
class SomeContainer;
class SomeElement: public iObject
{
A raw pointer to the parent object:
SomeContainer* Parent;
 
Search WWH ::




Custom Search