From 0b13bb321d07cf7ac751ff4308a37761eaa559f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=A4ckerlin?= Date: Mon, 11 Oct 2004 16:05:02 +0000 Subject: [PATCH] new AutoPtr --- mrw/auto.hpp | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/mrw/auto.hpp b/mrw/auto.hpp index 9eda272..9055993 100644 --- a/mrw/auto.hpp +++ b/mrw/auto.hpp @@ -9,6 +9,9 @@ @license LGPL, see file COPYING $Log$ + Revision 1.5 2004/10/11 16:05:02 marc + new AutoPtr + Revision 1.4 2004/10/07 09:24:08 marc enhance windoze compatibility @@ -146,6 +149,67 @@ namespace mrw { RESOURCE_TYPE _res; ///< the resource to be managed }; + template + class AutoPtr { + public: + /// @brief Construct from an allocated resource. + /// The resource is freed if necessary. + /// AutoPtr takes over ownership of the resource. + explicit AutoPtr(T* res = 0) + throw(std::bad_exception): _res(res) { + res = 0; + } + /// @brief Takeover ownership from another AutoPtr. + AutoPtr(AutoPtr& o) throw(std::bad_exception): + _res(o.release()) { + } + /// @brief Free resource. Calls @c reset(). + ~AutoPtr() throw(std::bad_exception) {reset();} + /// @brief Assign new resource. Calls @c reset(). + /// The resource is freed if necessary. + AutoPtr& operator=(T* res) throw(std::bad_exception) { + return reset(res); + } + /// @brief Takeover ownership from another AutoResorce. + /// Calls @c reset() from @c this and @c release() from @c other. + AutoPtr& operator=(AutoPtr& other) throw(std::bad_exception) { + return reset(other.release()); + } + /// @brief Get the resource. + operator T* const() const throw(std::bad_exception) { + return _res; + } + /// @brief get the resetted resource for resetting it. + /// Calls @c reset and returns the cleaned resource. + /// The intention is, that you can safely assign it a new value + /// (e.g. in an expression). + T* getClean() throw(std::bad_exception) { + reset(); + return _res; + } + /// @brief find out, if a value is set + /// @return @c true: resource is valid + operator bool() const throw(std::bad_exception) { + return _res!=0; + } + /// @brief Give away ownership of the resource. + /// @return old resource + T* release() throw(std::bad_exception) { + T* res(_res); _res=0; + return res; + } + /// @brief Assign a new resorce. + /// The old resource of @c this is freed if necessary. + AutoPtr& reset(T* res = 0) + throw(std::bad_exception) { + delete _res; + _res = res; + return *this; + } + private: + T* _res; ///< the resource to be managed + }; + /** @brief Automatically closes a file when destructed. @pre #include