可以自动销毁的Handle类

#include<stdio.h>
#include<Windows.h>
struct MyHandle {
	explicit MyHandle(HANDLE h = nullptr) :
		_h(h) {}
	~MyHandle() { Close(); }

	// 删除掉拷贝构造函数和赋值构造函数
	MyHandle(const MyHandle&) = delete;
	MyHandle& operator=(const MyHandle&) = delete;

	// ownership transfer   
	MyHandle(MyHandle&& other):_h(other._h) {
		other._h = nullptr;
	}
	// 赋值构造函数  两个&&是C++11引入的一种固定写法
	// 用来标识一个临时的右值引用
	MyHandle& operator=(MyHandle&& other)
	{
		// this是个指针,&other是取地址  所以完全正确
		if (this != &other) {
			Close();
			_h = other._h;
			other._h = nullptr;
		}
		// 指针解引用 是一个变量
		return *this;
	}
	operator bool() const {
		return _h != nullptr&&_h != INVALID_HANDLE_VALUE;
	}
	HANDLE Get() const {
		return _h;
	}
	void Close() {
		if (_h) {
			::CloseHandle(_h);
			_h = nullptr;
		}
	}
	// 隐式类型转换
	operator HANDLE() const
	{
		return _h; // Returns the real part as a double. 
	}
private:
	HANDLE _h;
};
int main()
{
	HANDLE mutex = CreateMutex(NULL,
		FALSE, TEXT("fuckyou"));
	MyHandle myHandle(mutex);
	if (myHandle) {
		printf("handle value 0x%08X\n", (HANDLE)myHandle);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值