Listing 1: The basic Handle template

// Copyright (c) 1997 by Bill Reck <breck@magna.com.au>
// This code may be used royalty-free as long as
// this notice appears in the product.

class null_rep {}; // Exception class used below

template <class REP, class ACCESS = REP*>
class Handle {
public:
    Handle(REP *rep = 0)
    : rep_(rep) {  // Claim a reference
        if ( rep_ != 0 ) rep_->incrRefCount();
    }
    Handle(const Handle<REP, ACCESS> &that)
    : rep_(that.rep_) { // Claim a reference
        if ( rep_ != 0 ) rep_->incrRefCount();
    }
    ~Handle() { // Release a reference
        if ( rep_ != 0 ) rep_->decrRefCount();
    }
    const Handle<REP, ACCESS> &operator = (
        const Handle<REP, ACCESS> &rhs) {
        // Claim a reference to the RHS and
        // release the old LHS reference
        REP *oldRep = rep_;
        rep_ = rhs.rep_;
        if ( rep_ != 0 ) rep_->incrRefCount();
        if ( oldRep != 0 ) oldRep->decrRefCount();
        return(*this);
    }
    ACCESS operator->() const {
        if ( rep_ == 0 ) throw null_rep();
        return(rep_); // Construct an ACCESS object
    }
    bool isNull() const { return(rep_ == 0); }
private:
    REP *rep_;
};
//End of File