Demonstrate a very simple safe pointer class.
#include <iostream>
#include <string>
using namespace std;
// The exception type thrown by the safe pointer.
class bad_ptr {
public:
string msg;
bad_ptr(string str) { msg = str; }
};
// A class used to demonstrate the safe pointer.
class myclass {
public:
int alpha;
int beta;
myclass(int p, int q) { alpha = p; beta = q; }
};
template <class T> class safe_ptr {
T *ptr;
public:
safe_ptr() { ptr = 0; }
T *operator->() {
if(!ptr != 0) throw bad_ptr("Attempt to use -> on null pointer.");
else return ptr;
}
T &operator*() {
if(!ptr) throw bad_ptr("Attempt to dereference null pointer.");
else return *ptr;
}
operator T *() { return ptr; }
T *operator=(T *val) { ptr = val; return ptr; }
};
int main()
{
safe_ptr<int> intptr;
try {
*intptr = 23;
cout << "The value pointed to by intptr is: " << *intptr << endl;
} catch(bad_ptr bp) {
cout << bp.msg << endl;
}
intptr = new int;
try {
*intptr = 23;
cout << "The value pointed to by intpr is: " << *intptr << "\n\n";
} catch(bad_ptr bp) {
cout << bp.msg << endl;
}
safe_ptr<myclass> mcptr;
try {
mcptr = new myclass(100, 200);
cout << "The values of alpha and beta for mcptr are: "
<< mcptr->alpha << " and " << mcptr->beta << endl;
mcptr->alpha = 27;
cout << "New value for mcptr->alpha: " << mcptr->alpha << endl;
cout << "Same as (*mcptr).alpha: " << (*mcptr).alpha << endl;
mcptr->beta = 99;
cout << "New value for mcptr->beta: " << mcptr->beta << "\n\n";
} catch(bad_ptr bp) {
cout << bp.msg << endl;
}
safe_ptr<myclass> mcptr2;
try {
mcptr2->alpha = 88;
} catch(bad_ptr bp) {
cout << bp.msg << endl;
}
delete intptr;
delete mcptr;
return 0;
}
Related examples in the same category