00001 #ifndef LUX_SCOPED_PTR_H 00002 #define LUX_SCOPED_PTR_H 00003 00004 #include <cstring> 00005 #include <string> 00006 00007 namespace Lux { 00008 00009 template<class T> class scoped_ptr { 00010 private: 00011 T * ptr_; 00012 scoped_ptr(scoped_ptr const &); 00013 scoped_ptr & operator=(scoped_ptr const &); 00014 typedef scoped_ptr<T> this_type; 00015 00016 public: 00017 typedef T element_type; 00018 explicit scoped_ptr(T * p = 0): ptr_(p) {} 00019 virtual ~scoped_ptr() { delete ptr_; } 00020 void reset(T * p = 0) { 00021 delete ptr_; 00022 ptr_ = p; 00023 } 00024 T & operator*() const { return *ptr_; } 00025 T * operator->() const { return ptr_; } 00026 T * get() const { return ptr_; } 00027 }; 00028 00029 template<class T> class scoped_array { 00030 private: 00031 T * ptr_; 00032 scoped_array(scoped_array const &); 00033 scoped_array & operator=(scoped_array const &); 00034 typedef scoped_array<T> this_type; 00035 00036 public: 00037 typedef T element_type; 00038 explicit scoped_array(T * p = 0): ptr_(p) {} 00039 virtual ~scoped_array() { delete [] ptr_; } 00040 void reset(T * p = 0) { 00041 delete [] ptr_; 00042 ptr_ = p; 00043 } 00044 T & operator*() const { return *ptr_; } 00045 T * operator->() const { return ptr_; } 00046 T * get() const { return ptr_; } 00047 T & operator[](size_t i) const { return ptr_[i]; } 00048 }; 00049 00050 class scoped_string: public scoped_array<char> { 00051 public: 00052 explicit scoped_string() { reset_string(""); } 00053 explicit scoped_string(const std::string &str) { 00054 reset_string(str); 00055 } 00056 00057 void reset_string(const std::string &str) { 00058 char *p = new char[str.size() + 1]; 00059 strcpy(p, str.c_str()); 00060 reset(p); 00061 } 00062 00063 void reset_string(const char *str) { 00064 char *p = new char[std::strlen(str) + 1]; 00065 strcpy(p, str); 00066 reset(p); 00067 } 00068 }; 00069 } 00070 #endif