// A Simple handle class that uses copying.
#include <string>
#include <iostream>
template < typename T >
class handle {
public:
handle() : tp(0) { }
handle(T * tp) : tp(tp) { }
~handle(void) {
delete tp;
}
handle(const handle & th) : tp(th.tp ? th.tp->clone() : 0) { }
handle & operator = (const handle & th) {
if (this != &th) {
delete tp;
tp = th.tp ? th.tp->clone() : 0;
}
return *this;
}
operator bool (void) const {
return tp;
}
T & operator * (void) {
assert(tp);
return *tp;
}
T * operator -> (void) {
assert(tp);
return tp;
}
private:
T * tp;
};
struct widget {
widget(std::string str) : str(str) {
std::cerr << "Creating a " << str << " widget.\n";
}
~widget() {
std::cerr << "Deleting a " << str << " widget.\n";
}
widget * clone(void) const { return 0; }
const std::string str;
};
int main() {
handle<widget> w1h = new widget("red");
if (w1h) {
handle<widget> w2h = new widget("blue");
try {
handle<widget> w3h = new widget("green");
throw(1);
}
catch (int) { }
}
}
// $Log: c-handle.cc,v $
// Revision 1.1 2002/04/25 13:03:45 rclayton
// Initial revision
//
syntax highlighted by Code2HTML, v. 0.9