#include #include #include using namespace std; class BoardT{ public: BoardT(string n):name(n){ cout << "Creating board " << name << endl; } ~BoardT() { cout << "Destroying board " << name << endl; } string Name(void) const{ return name;} int Width(void) const { return w;} int Height(void) const { return h;} int Data(int x, int y) const{ return y*w + x;} private: int w =5, h = 7; int * data; // pretend this is allocated in the constructor string name; }; template class Handle { public: // default constructor, takes a pointer to the item Handle( T * item): rep(item), count(new int(1)){} // copy constructor, increment the count Handle(const Handle & other):rep(other.rep), count(other.count) { (*count)++; } ~Handle() { if(*count == 1) { delete count; delete rep; } else { (*count)--; } } Handle & operator = (const Handle * other) { // if we are copying a handle to the thing we are pointing // at, ignore it. if (rep = other.rep) { return * this; } if (*count == 1) { // we are the last of our handles // get rid of what we are pointing at. delete count; delete rep; } else { // decrement our old handles by one (*count)--; } count = other.count; (*count) ++; rep = other.rep; return this; } T* operator -> () { return rep; } private: T * rep; int * count; }; typedef Handle Board; void PrintBoard(Board aboard); int main() { BoardT * board = new BoardT("first one"); Board myBoard(board); Board aBoard(new BoardT("The Second One")); Board b2(myBoard); Board b3(myBoard); cout << myBoard->Name() << endl; PrintBoard(myBoard); return 0; } void PrintBoard(Board aboard) { int i,j; for(i =0; i < aboard->Height(); i++) { for (j = 0; j < aboard->Width(); j++) { cout << setw(4) << aboard->Data(j,i); } cout << endl; } cout << endl; return; }