new AutoPtr
This commit is contained in:
64
mrw/auto.hpp
64
mrw/auto.hpp
@@ -9,6 +9,9 @@
|
||||
@license LGPL, see file <a href="license.html">COPYING</a>
|
||||
|
||||
$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 <typename T>
|
||||
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 <mrw/auto.hpp>
|
||||
|
||||
|
Reference in New Issue
Block a user