Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct WinHandleTraits
- {
- typedef HANDLE handle_type;
- static BOOL Destroy(HANDLE h)
- {
- return ::CloseHandle(h);
- }
- static HANDLE InvalidHandle(void)
- {
- return NULL;
- }
- };
- template <class HandleTraits , BOOL t_Owner = TRUE>
- class CHandleT : public HandleTraits
- {
- public:
- typedef typename HandleTraits::handle_type handle_type;
- private:
- handle_type m_h;
- typedef CHandleT<HandleTraits, t_Owner> _ThisClass;
- public:
- CHandleT(handle_type h = HandleTraits::InvalidHandle()) :m_h(h)
- {
- //
- }
- CHandleT(_ThisClass& h) :m_h(HandleTraits::InvalidHandle())
- {
- Assign(h);
- }
- ~CHandleT()
- {
- BOOL res = CloseHandle();
- _ASSERTE(res);
- }
- BOOL CloseHandle(void)
- {
- BOOL res = TRUE;
- if (IsOwner() && IsHandleValid()) {
- if (res = HandleTraits::Destroy(m_h))
- m_h = HandleTraits::InvalidHandle();
- }
- else if (!IsOwner()) {
- m_h = HandleTraits::InvalidHandle();
- }
- return res;
- }
- BOOL IsOwner(void) const
- {
- return t_Owner;
- }
- BOOL IsHandleValid(void) const
- {
- return m_h != HandleTraits::InvalidHandle();
- }
- // this will destroy any previous handle, if its owner
- BOOL AttachHandle(handle_type h)
- {
- BOOL res = CloseHandle();
- if (res) {
- m_h = h;
- }
- return res;
- }
- handle_type DetachHandle(void)
- {
- handle_type hOld = m_h;
- m_h = HandleTraits::InvalidHandle();
- return hOld;
- }
- // takes ownership if _ThisClass owns the handle
- _ThisClass& Assign(_ThisClass& rhs)
- {
- if (GetHandle() != rhs.GetHandle()) {
- BOOL res = AttachHandle(rhs.DetachHandle());
- _ASSERTE(res);
- }
- return *this;
- }
- _ThisClass& Assign(handle_type t)
- {
- BOOL res = AttachHandle(t);
- _ASSERTE(res);
- return *this;
- }
- operator handle_type() const
- {
- return m_h;
- }
- const handle_type& GetHandle(void) const
- {
- return m_h;
- }
- handle_type& GetHandle(void)
- {
- return m_h;
- }
- _ThisClass& operator = (_ThisClass& rhs)
- {
- return Assign(rhs);
- }
- _ThisClass& operator = (handle_type h)
- {
- return Assign(h);
- }
- BOOL operator == (handle_type h) const
- {
- return m_h == h ? TRUE : FALSE;
- }
- BOOL operator != (handle_type h) const
- {
- return m_h != h ? TRUE : FALSE;
- }
- };
- // win32 handle resource
- typedef CHandleT<WinHandleTraits, TRUE> CWinHandle;
- int main()
- {
- CWinHandle handle;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement