Changeset - r19013:4e601f65c8d6
[Not reviewed]
master
0 1 0
michi_cc - 13 years ago 2012-02-04 13:28:35
michi_cc@openttd.org
(svn r23880) -Add: A simple smart pointer.
1 file changed with 34 insertions and 0 deletions:
0 comments (0 inline, 0 general)
src/core/alloc_type.hpp
Show inline comments
 
@@ -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 */
0 comments (0 inline, 0 general)