|
Joshua
open source statistical hierarchical phrase-based machine translation system
|
00001 #ifndef UTIL_SCOPED__ 00002 #define UTIL_SCOPED__ 00003 00004 /* Other scoped objects in the style of scoped_ptr. */ 00005 00006 #include <cstddef> 00007 #include <cstdio> 00008 00009 namespace util { 00010 00011 template <class T, class R, R (*Free)(T*)> class scoped_thing { 00012 public: 00013 explicit scoped_thing(T *c = static_cast<T*>(0)) : c_(c) {} 00014 00015 ~scoped_thing() { if (c_) Free(c_); } 00016 00017 void reset(T *c) { 00018 if (c_) Free(c_); 00019 c_ = c; 00020 } 00021 00022 T &operator*() { return *c_; } 00023 const T&operator*() const { return *c_; } 00024 T &operator->() { return *c_; } 00025 const T&operator->() const { return *c_; } 00026 00027 T *get() { return c_; } 00028 const T *get() const { return c_; } 00029 00030 private: 00031 T *c_; 00032 00033 scoped_thing(const scoped_thing &); 00034 scoped_thing &operator=(const scoped_thing &); 00035 }; 00036 00037 class scoped_fd { 00038 public: 00039 scoped_fd() : fd_(-1) {} 00040 00041 explicit scoped_fd(int fd) : fd_(fd) {} 00042 00043 ~scoped_fd(); 00044 00045 void reset(int to) { 00046 scoped_fd other(fd_); 00047 fd_ = to; 00048 } 00049 00050 int get() const { return fd_; } 00051 00052 int operator*() const { return fd_; } 00053 00054 int release() { 00055 int ret = fd_; 00056 fd_ = -1; 00057 return ret; 00058 } 00059 00060 private: 00061 int fd_; 00062 00063 scoped_fd(const scoped_fd &); 00064 scoped_fd &operator=(const scoped_fd &); 00065 }; 00066 00067 class scoped_FILE { 00068 public: 00069 explicit scoped_FILE(std::FILE *file = NULL) : file_(file) {} 00070 00071 ~scoped_FILE(); 00072 00073 std::FILE *get() { return file_; } 00074 const std::FILE *get() const { return file_; } 00075 00076 void reset(std::FILE *to = NULL) { 00077 scoped_FILE other(file_); 00078 file_ = to; 00079 } 00080 00081 private: 00082 std::FILE *file_; 00083 }; 00084 00085 // Hat tip to boost. 00086 template <class T> class scoped_array { 00087 public: 00088 explicit scoped_array(T *content = NULL) : c_(content) {} 00089 00090 ~scoped_array() { delete [] c_; } 00091 00092 T *get() { return c_; } 00093 const T* get() const { return c_; } 00094 00095 T &operator*() { return *c_; } 00096 const T&operator*() const { return *c_; } 00097 00098 T &operator->() { return *c_; } 00099 const T&operator->() const { return *c_; } 00100 00101 T &operator[](std::size_t idx) { return c_[idx]; } 00102 const T &operator[](std::size_t idx) const { return c_[idx]; } 00103 00104 void reset(T *to = NULL) { 00105 scoped_array<T> other(c_); 00106 c_ = to; 00107 } 00108 00109 private: 00110 T *c_; 00111 }; 00112 00113 } // namespace util 00114 00115 #endif // UTIL_SCOPED__