Reliable Software Logo
 Home  >  C++ Resources  > Resource Management   >  Resource Management in Action

Strong Pointers and Resource Management in C++

Resource Management in Action

If you're a seasoned developer, you know painfully well how much time is regularly wasted tracking resource bugs. I don't have to convince you that the little time you and your team spend familiarizing yourselves with the principles of Resource Management will pay over and over. You can start using this methodology immediately, whether you're starting a new project from scratch or are in the middle of an existing project. The conversion doesn't have to be done all at once. Here are the steps.

First of all, make the basic strong templates available in your project. You can download them from our web site. Then start encapsulating naked pointers one-by-one. You'll find naked pointers by searching your code for calls to new.

The easiest ones to encapsulate are the temporary pointers that are used within a single procedure. Just replace them with auto_ptrs and remove the (hopefully) matching calls to delete. If a pointer is not deleted within the procedure, but rather is returned from it, replace it with an auto_ptr and call the release method before returning its contents. You'll deal with the calls to release in your second pass. Notice that, even at this early point, your code will gain in robustness--you'll have removed potential leaks resulting from unexpected returns from the middle of a procedure and from exceptions.

Naked pointers within objects go next. Make sure they are either encapsulated in separate auto_ptrs or allocated in constructors and deallocated in destructors. Again, if you have to pass the ownership, call the release method. If you have containers that own objects, re-implement them using strong vectors.

Next, find all the calls to release and try to eliminate as many as possible. If release is called in order to return a pointer, make the function return an auto_ptr by value. Of course, the callers will have to be changed too. They'll have to use auto_ptrs to receive the results of such calls.

Repeat this procedure until the only calls to new and release occur within constructors or are parts of direct resource transfers. At that point you'll be done with memory leaks inside your code. Do the same with other kinds of resources your program uses.

You'll notice how Resource Management eliminates a lot of complexities related to error and exception handling. Not only will your code become more robust, it will actually become simpler and easier to maintain.

Example

Resource Management pops up virtually in every non-trivial programming exercise. Not long ago I had the opportunity to listen to an interesting talk given by Andrew Koenig at the C++ World conference. He spoke about the standard library and, to round things up, gave an example of simple implementation of topological sort. What made the implementation simple and elegant was the use of the facilities of the standard library--string, vectors, maps and iterators.

I liked his implementation, but it wasn't the kind of solution I would have come up with. In particular it cleverly avoided all memory management problems. Obviously, if you can avoid memory management, you should. But that's not always possible and, besides, not always most efficient. I started thinking about an alternative approach that would deal explicitly with the problems of allocating and de-allocating objects.

I will first describe the implementation based on Andrew Koenig's talk (I call it string-based) and then transform it into a more explicitly Resource-Management-based solution. In the process I'll explain some of the tradeoffs and unveil some of the resource management tricks of the standard library.

I would like to thank Andrew Koenig for letting me use his example and discussing the tradeoffs with me.

Topological Sort

Here's a short description of the problem. The program is given a list of pairs of strings. The second element of each pair, the successor, is meant to depend on the first element of the pair, the predecessor. After reading all the pairs, the program outputs the strings in an order that fulfills the following condition: no successor is output before its predecessor. There could be many acceptable orderings, or, in case of cyclic dependencies, there could be none. In the latter case, the program should print the appropriate failure message.

This problem arises whenever you have to schedule several inter-dependent tasks. For instance, you might think of the process of dressing up. You have to put on a shirt, pants, socks, shoes, etc. Some of these items can be put in any order; others depend on each other. For instance, it's impractical to put on shoes before putting on socks. The dependencies between various items of clothing can be expressed as a list of pairs, for instance:

LeftSock        LeftShoe
RightSock    	RightShoe
Pants           LeftShoe
Pants           RightShoe

Our program, given a list like that, should produce the output that describes one possible order of putting on various items of dress. For instance, the list

LeftSock RightSock Pants LeftShoe RightShoe

fulfills the constraints of our problem.

The algorithm that creates such a list, given a list of dependencies, is called topological sort. Here's how it works.

For each item store a count of predecessors and a list of successors. For instance, for Pants you'd store zero predecessors and a list of LeftShoe, RightShoe as successors. For LeftShoe you'd count one predecessor (LeftSock) and store an empty list of successors, etc. Items whose predecessor count is zero can be immediately output--they have no dependencies. Each time you output such an item, go through its list of successors and decrement their predecessor count. Again, these items whose predecessor count goes to zero are ready to be output. You know you've been successful if you are able to output all items using this procedure.

String-Based Approach

This is my version of the Andrew Koenig's implementation. The information about each item is stored inside the Item object. It is just a count of predecessors and a list of successors, together with methods to manipulate and access them.

class Item
{
public:
    typedef vector<string>::iterator iter;

    Item () : _predCount (0) {}
    int PredCount () const { return _predCount; }
    void IncPred () { _predCount++; }
    void DecPred () { _predCount--; }
    void AddSucc (string str)
    {
        _succ.push_back (str);
    }
    iter begin () { return _succ.begin (); }
    iter end () { return _succ.end (); }
private
    int _predCount;
    vector<string> _succ;
};

Notice that successors are stored by name in a vector of strings. Access to successors is given by means of an iterator. It's a standard vector iterator which we typedef'd for convenience to Item::iter.

The name of the item itself is not stored in the Item. That's because the main data structure in this implementation is a standard map that maps names to Items.

Here's how this map is filled with the initial data:

void InputData (map<string, Item> & itemMap)
{
    string pred, succ;
    while (cin >> pred >> succ)
    {
        itemMap [pred].AddSucc (succ);
        itemMap [succ].IncPred ();
    }
}

An important point to remember, when dealing with maps, is that the mere action of subscripting a map creates a new entry, if one is not already there. In such a case, the default constructor is used to initialize the Item.

After filling the map with string/item pairs, we create a vector, zeroes, of items whose predecessor count is zero. Again, notice that items are stored in this vector by name, using strings. These items are ready to be output at any time, since they have no dependencies.

vector<string> zeroes;
map<string, Item>::iterator it;
for (it = itemMap.begin (); it != itemMap.end (); ++it)
{
    pair<string, Item> p = *it;
    if (p.second.PredCount () == 0)
        zeroes.push_back (p.first);
}

The map iterator returns key/value pairs. You access the key part of the pair as its first element, and the value part as its second element. In our case the key is a string and the value is an Item.

Now we are ready to start outputting the elements. We pop them from our vector of zeroes. Notice that it's a two-step process--we access the top element of the vector using back, and destroy it using pop_back. The standard library is designed in such a way that the method pop_back does not return the popped element.

After an element has been output, we go through its list of successors and decrement their respective predecessor counts. Those items whose predecessor counts go to zero become ready to be output during the following iterations. We add them to our vector of zeroes.

int count = 0;
while (zeroes.size () != 0)
{
    string str = zeroes.back ();
    cout << str << endl;
    count++;
    zeroes.pop_back ();
    // Iterate over successors
    Item & item = itemMap [str];
    for (Item::iter itSuc = item.begin (); 
        itSuc != item.end (); ++itSuc)
    {
        Item & suc = itemMap [*itSuc];
        suc.DecPred ();
        if (suc.PredCount () == 0)
            zeroes.push_back (*itSuc);
    }
}

Finally, the measure of our success is the equality between the original number of items in the map and the number of items that we have output.

return count == itemMap.size ();

Discussion

This is an elegant and reasonably efficient implementation of topological sort. There is however something very non-C-like about it. Notice the way items are indirectly addressed using strings. The traditional C way would be to use pointers. Why isn't the list of successors, for instance, implemented as a vector of pointers? Same with the vector of zeroes. Pointer implementation would eliminate all these redundant map lookups. Innocent looking statements like

Item & suc = itemMap [*itSuc];

are not what they look like. Indexing into a map is not a constant-time operation. It's not a big deal--a log-time search in a balanced tree involving some string comparisons. But do we really have to sacrifice performance, and for what reason?

C programmers are usually very aware of little inefficiencies like these. So there must have been a good reason why this solution was chosen. Well, do you see any explicit memory allocation in this whole program? There is none! All the resource management is done behind the scenes. The design of this program was influenced by the attempt to avoid dealing with dynamic resources. It was possible to attain this goal by judicious use of value semantics and a very clever resource-management scheme implemented by the standard library's string. In fact, most implementations of the standard string come very close to what other languages call garbage collection.

Standard containers were designed to work with values. In this program, both Items and strings are being internally treated as values--they are copied and passed around as if they were integers or doubles. For instance, when necessary, the map allocates a node with enough room to hold a string and an Item. The string is then copied into its space and the Item initialized using its default constructor. Since the map was designed to take care of the management of its nodes, the client doesn't have to worry about any allocations or de-allocations.

In terms of Resource Management, the usual implementation of the standard string is in terms of a strong reference-counting pointer with a twist. Internally it contains a pointer to the actual storage area for the characters. This storage area has room for reference count (in most implementations, it's in the same array at offset –1). So whenever you're passing a string "by value," or assigning it to another string, you're not actually copying the characters--you're just incrementing their reference count.

The twist is that the characters are copied when you're trying to write into a string whose internal storage is shared with other strings. This is called copy-on-write, or COW for short. From the clients' point of view, it looks like they're always dealing with separate copies of strings, but they only pay the cost of copying when it actually matters. The downside of this scheme is that such behind-the-scenes manipulations of shared data might get ugly when multiple threads are involved. Synchronizing access at such a low level might be costly.

Resource-Management Approach

The alternative to a string-based approach is to take resource management in our own hands.

First of all, let's combine the string and the item into a single data structure called Node. This time, however, the list of successor will be implemented as a vector of pointers to Nodes. Since the same node may appear on several lists of successors, the list can't be the sole owner of a Node. The simplest solution in such a case is to treat these pointers to Nodes as weak pointers. That means, in particular, that we'll have to provide a separate "owner" data structure for them. Here's the declaration of Node:

class Node
{
public:
    typedef std::vector<Node *>::iterator iter;

    Node (string name): _name (name), _predCount (0) {}
    string GetName () { return _name; }
    void IncPred () { _predCount++; }
    void DecPred () { _predCount--; }
    void AddSucc (Node * node)
    {
        _succ.push_back (node);
    }
    int PredCount () const { return _predCount; }
    iter begin () { return _succ.begin (); }
    iter end () { return _succ.end (); }
private
    string            _name;
    int               _predCount;
    vector<Node *>    _succ;  // weak pointers
};

The owner of all the nodes will be a strong vector, nodeOwner. We'll use the auto_vector introduced previously. Conceptually, you might think of it as a standard vector of auto_ptr, keeping in mind the particularities of such implementation.

This is the code in main that creates and fills the auto_vector:

auto_vector<Node> nodeOwner;
InputData (nodeOwner);

We fill this vector with dynamically allocated nodes--one node per unique input string. The input algorithm is pretty straightforward. We still have to keep a map of string/node pairs in order to avoid allocating multiple nodes for the same string, but the lifetime of this map is limited to the duration of the input process.

void InputData (auto_vector<Node> & nodeOwner)
{
    map<string, Node *> itemMap;

    string pred, succ;
    while (cin >> pred >> succ)
    {
        Node * node1 = itemMap [pred];
        if (node1 == 0)
        {
            auto_ptr<Node> node (new Node (pred));
            node1 = node.get ();
            itemMap [pred] = node1;
            nodeOwner.push_back (node);
        }
        Node * node2 = itemMap [succ];
        if (node2 == 0)
        {
            auto_ptr<Node> node (new Node (succ));
            node2 = node.get ();
            itemMap [succ] = node2;
            nodeOwner.push_back (node);
        }

        node1->AddSucc (node2);
        node2->IncPred ();
    }
}

Notice the application of standard Resource Management rules. A new node is allocated in the context of the constructor of an auto_ptr. The ownership of the Node is transferred from the auto_ptr to the nodeOwner by passing it by value. The order of statements is important here. The auto_ptr should not be accessed after performing the push_back--such code would not work with the newer implementations of the standard library.

As before, we create a vector of items whose predecessor count is zero. This time, however, it's a vector of (weak) pointers to Nodes. We pre-fill it by iterating over the strong vector of Nodes. Remember that we have provided the auto_vector with a special iterator that returns pointers rather than auto_ptrs. (This way we won't transfer the ownership of Nodes by accident.)

vector<Node *> zeroes;
typedef auto_vector<Node>::iterator Iter;
Iter it = nodeOwner.begin ();
Iter end = nodeOwner.end ();
for (; it != end; ++it)
{
    Node * node = *it;
    if (node->PredCount () == 0)
        zeroes.push_back (node);
}

The main loop of the algorithm is simplified by the fact that we can now access the successors of each element directly, rather than by going through string lookup.

int count = 0;
while (zeroes.size () != 0)
{
    Node * node = zeroes.back ();
    cout << node->GetName () << endl;
    count++;
    zeroes.pop_back ();
    for (Node::iter itSuc = node->begin (); 
        itSuc != node->end (); ++itSuc)
    {
        Node * nodeSuc = *itSuc;
        nodeSuc->DecPred ();
        if (nodeSuc->PredCount () == 0)
            zeroes.push_back (nodeSuc);
    }
}

Tidying up

I have deliberately gone through this rather minimalistic translation of a string-based algorithm into a resource-management-aware algorithm. The resulting implementation may be polished some more. For instance, it makes perfect sense to hide the details of Node management in a special-purpose class, NodeAdder.

class NodeAdder
{
public:
    NodeAdder (auto_vector<Node> > & nodeOwner)
        :_nodeOwner (nodeOwner)
    {}
    Node * GetNode (string const & name)
    {
        map<string, Node *>::iterator it = _itemMap.find (name);
        if (it != _itemMap.end ())
            return it->second;

        auto_ptr<Node> newNode (new Node (name));
        Node * node = newNode.get ();
        _itemMap [name] = node;
        _nodeOwner.push_back (newNode);
        return node;
    }
private
    auto_vector<Node> & _nodeOwner;
    map<string, Node *> _itemMap;
};

Notice the use of the map's find method where we previously accessed it through associative indexing. This way we avoid creating a temporary empty map entry in case the string is not found.

Our InputData procedure is now considerably simpler.

void InputData (auto_vecor<Node> & nodeOwner)
{
    NodeAdder nodes (nodeOwner);
    string pred, succ;
    while (cin >> pred >> succ)
    {
        Node * node1 = nodes.GetNode (pred);
        Node * node2 = nodes.GetNode (succ);
        node1->AddSucc (node2);
        node2->IncPred ();
    }
}

Performance

My program is obviously more complicated that the original string-based program presented by Andrew Koenig (making his version a better choice for a conference). It exposes the plumbing of Resource Management, especially during the initial input phase of the algorithm. So is it at least faster?

I instrumented both versions and ran them over a large data set. Here are the results (the "stringy" one uses strings, and the "strongy" one, strong pointers):

E:\Work\topo\stringy>release\stringy < pairs.txt > sorted.txt
Processing 23617 pairs
Elapsed clocks: 3325

E:\Work\topo\strongy>release\strongy < pairs.txt > sorted.txt
Processing 23617 pairs
Elapsed clocks: 2213

As you can see, there indeed is a visible performance gain (33% in this case). It is not spectacular, since my implementation only cuts down on logarithmic-time lookups, but it's there! It's always good to know what the tradeoffs are.

You can download the source code for these examples.

Conclusion

I have shown two implementations of the same algorithm, both taking advantage of the "new C++," the high-level language that C++ evolved into after the introduction of the standard template library. The use of C++ in the first implementation is reminiscent of the string manipulating languages, like Perl. The second implementation gives more control to the programmer. It makes the resource-management part of the program more obvious and, at the same time, separates it from the main part of the algorithm. It also gets rid of the little inefficiencies of the first implementation. Finally, it generalizes easily to situations where there is no obvious string representation for the items to be topologically sorted.

Bibliography

  1. Bartosz Milewski, Resource Management in C++, Journal of Object Oriented Programming, March/April 1997, Vol. 10, No 1. p. 14-22
  2. Bjarne Stroustrup, C++ Programming Language, Third Edition, Addison-Wesley (1997). Examples of resource management could be found in the Bjarne Stroustrup's famous book since its first edition. The latest one he has a section on resource management.