/****************************************************************************** *** FILE: RobotPtr.h *** DATE: 03/21/2004 *** AUTHOR: Nicolai M. Josuttis *** see Object-oriented programming in C++, chapter9, sectin 2 *** GOAL: This example that illustrates how to redeifine operators * and -> *** to develop a new class of smart pointers that behave like a *** garbage collector. That is, the object gets deleted when there is *** no pointerts pointing at it left. ******************************************************************************/ #ifndef _ROBOT_PTR_ #define _ROBOT_PTR_ #include "Robot.h" class RobotPtr { private: Robot *ptr; // the pointer to a Robot object int *counter; // we need to share the counter for all smart pointers // that point to the same Robot object void release(); public: RobotPtr(Robot *r=NULL) : ptr(r) { counter = new int; *counter=1; }; ~RobotPtr() { release(); }; RobotPtr& operator=(const RobotPtr& p); Robot& operator*() { return *ptr; }; Robot* operator->() { return ptr; }; }; #endif