#include template class smart_ptr { public: T* operator->() {if(ptr) return ptr; throw -1;} T& operator*() {if(ptr) return *ptr; return NULL;} smart_ptr() {ptr = NULL;} smart_ptr(T* p):ptr(p) {} ~smart_ptr() {if (ptr) delete(ptr); ptr = NULL;} smart_ptr& operator=(T* p) {if(ptr) delete(ptr); ptr = p; return *this;} bool operator==(const T& p1) {return (p1.ptr == ptr);} bool operator==(const int i) {return (i == (int)ptr);} protected: T* ptr; }; class myclass { public: int a; int b; myclass() {printf("\n new myclass object created.");} ~myclass() {printf("\n myclass object deleted.");} }; //test1: one smart_ptr assgined twice void test1() { smart_ptr pObj1 = new myclass; pObj1->a = 100; pObj1 = new myclass; } //test2: assigning one smart_ptr to another void test2() { smart_ptr pObj1; pObj1 = new myclass; smart_ptr pObj2; pObj2 = pObj1; } //test3: using uninitialized pointer void test3() { try { smart_ptr pObj1; pObj1->a = 100; } catch(int e) { printf("\n invalid pointer reference"); } } int main() { printf("\ntest1"); test1(); //printf("\ntest2"); //test2(); printf("\ntest3"); test3(); printf("\nend of program\n"); return 0; }