#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;
}
可以自动销毁的Handle类
于 2024-05-29 00:03:17 首次发布