sooksjb 阅读(3) 评论(0)

在Windows编程中,HANDLE根据不同的对象有不同的返回值,例如普通处理对象的无效值是NULL、

文件处理对象的无效值是INVALID_HANDLE_VALUE。

现对HANDLE进行封装,方便使用和扩展。

头文件

#pragma once

class CNullHandle
{
public:
CNullHandle(HANDLE h = NULL);
~CNullHandle();

void operator = (HANDLE h);
void Attach(HANDLE h);
void Close();
BOOL IsNull() const;
operator HANDLE () const;

public:
HANDLE m_handle;
};

class CInvalidHandle
{
public:
CInvalidHandle(HANDLE h = INVALID_HANDLE_VALUE);
~CInvalidHandle();

void operator = (HANDLE h);
void Attach(HANDLE h);
void Close();
BOOL IsNull() const;
operator HANDLE () const;

public:
HANDLE m_handle;
};

template<class T>
class CWinHandle
{
public:
CWinHandle(T h = NULL)
:m_h(h)
{
}
~CWinHandle()
{
}

void operator = (HANDLE h)
{
m_h = h;
}

void Attach(HANDLE h)
{
m_h.Attach(h);
}

void Close()
{
m_h.Close();
}

BOOL IsNull() const
{
return m_h.IsNull();
}

operator HANDLE () const
{
return m_h;
}

private:
T m_h;
};

实现文件

#include "stdafx.h"
#include "WinHandle.h"

CNullHandle::CNullHandle(HANDLE h/* = NULL*/)
:m_handle(h)
{
}

CNullHandle::~CNullHandle()
{
Close();
}

void CNullHandle::operator = (HANDLE h)
{
Attach(h);
}

void CNullHandle::Attach(HANDLE h)
{
if (NULL != m_handle && m_handle != h)
{
CloseHandle(m_handle);
m_handle = h;
}
}

void CNullHandle::Close()
{
if (NULL != m_handle)
{
CloseHandle(m_handle);
m_handle = NULL;
}
}

BOOL CNullHandle::IsNull() const
{
return (NULL == m_handle);
}

CNullHandle::operator HANDLE () const
{
return m_handle;
}

CInvalidHandle::CInvalidHandle(HANDLE h/* = INVALID_HANDLE_VALUE*/)
:m_handle(h)
{
}

CInvalidHandle::~CInvalidHandle()
{
Close();
}

void CInvalidHandle::operator = (HANDLE h)
{
Attach(h);
}

void CInvalidHandle::Attach(HANDLE h)
{
if (INVALID_HANDLE_VALUE != m_handle && m_handle != h)
{
CloseHandle(m_handle);
m_handle = h;
}
}

void CInvalidHandle::Close()
{
if (INVALID_HANDLE_VALUE != m_handle)
{
CloseHandle(m_handle);
m_handle = INVALID_HANDLE_VALUE;
}
}

BOOL CInvalidHandle::IsNull() const
{
return (INVALID_HANDLE_VALUE == m_handle);
}

CInvalidHandle::operator HANDLE () const
{
return m_handle;
}