Things to Watch Out For When Using Smart Pointers

Basic Types

The smart pointers do not work with basic types such as int, long, and char.

Key Collections

If you implement a key collection containing element pointers, you must define your key function with the element as input, not the pointer to the element, for example:

typedef IKeySortedSet<IMngElemPointer<Element>,int> keySortedSetOfPointers;

int const& key(Element const& element)
{
    return element.elementKey();
}

where elementKey returns the element's key.

Automatic Pointer Copy Constructor and Assignment Operator

An automatic pointer's copy constructor and assignment operator are defined in a way that resets the source pointer to NULL. This prevents multiple automatic pointers from pointing to the same element. In the following example, p2 is implicitly set to NULL:

IAutoPointer<SomeType> p1, p2;
...
p1 = p2;

However, the copy constructor and assignment operator still take a const argument (using a const cast-away) to maintain compliance with the standard interface for these operations. This standard interface is required, for example, when you use these types as element types in collections, because the copy constructor and assignment operator are required to have such an interface. (Otherwise, the collection's add function could not take a const argument.)

Managed Pointers and Copying Elements

If you want to create managed pointers for a collection and copy in elements from a second collection that already contains managed pointers, you cannot use IINIT because it will destroy the managed pointers in the second collection. To avoid this situation, you can use the following notation:

typedef IMngElemPointer<PersonPtr> MyClassPtr;
typedef IKeySet<MyClassPtr> MyAddressList;

MyClassPtr pMyClass;
pMyClass = Business.elementWithKey(...);

In the above notation, Business is the collection from the previous examples, but here it is an IKeySet collection rather than an ISet collection so that elementWithKey can be used.



Introduction to the Collection Classes
Collection Class Hierarchy
Overall Implementation Structure
Adding Elements
Removing Elements
Replacing Elements
Smart Pointers


Choosing the Appropriate Smart Pointer Class
Constructing Smart Pointers
Using Automatic Pointers
Using Element Pointers
Using Managed Pointers
Copying and Referencing Collections
Instantiating the Collection Classes