diff options
author | michi_cc <michi_cc@openttd.org> | 2012-02-04 13:28:35 +0000 |
---|---|---|
committer | michi_cc <michi_cc@openttd.org> | 2012-02-04 13:28:35 +0000 |
commit | 9d72b47984f61d0c2bb724fa7bf6d54f988384c9 (patch) | |
tree | e16629318bd525bf53eb5d6ce7532b44c9d22a5f /src/core | |
parent | 1b0bd457589383f8f5755c5edb66a1498bb125ef (diff) | |
download | openttd-9d72b47984f61d0c2bb724fa7bf6d54f988384c9.tar.xz |
(svn r23880) -Add: A simple smart pointer.
Diffstat (limited to 'src/core')
-rw-r--r-- | src/core/alloc_type.hpp | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/core/alloc_type.hpp b/src/core/alloc_type.hpp index 6caaf916a..9c25cc9e3 100644 --- a/src/core/alloc_type.hpp +++ b/src/core/alloc_type.hpp @@ -180,4 +180,38 @@ public: inline void operator delete[](void *ptr) { free(ptr); } }; +/** + * A smart pointer class that free()'s the pointer on destruction. + * @tparam T Storage type. + */ +template <typename T> +class AutoFreePtr +{ + T *ptr; ///< Stored pointer. + +public: + AutoFreePtr(T *ptr) : ptr(ptr) {} + ~AutoFreePtr() { free(this->ptr); } + + /** + * Take ownership of a new pointer and free the old one if needed. + * @param ptr NEw pointer. + */ + inline void Assign(T *ptr) + { + free(this->ptr); + this->ptr = ptr; + } + + /** Dereference pointer. */ + inline T *operator ->() { return this->ptr; } + /** Dereference pointer. */ + inline const T *operator ->() const { return this->ptr; } + + /** Cast to underlaying regular pointer. */ + inline operator T *() { return this->ptr; } + /** Cast to underlaying regular pointer. */ + inline operator const T *() const { return this->ptr; } +}; + #endif /* ALLOC_TYPE_HPP */ |