Last active
February 25, 2021 01:08
-
-
Save LYP951018/491388d7644cfc6f32c876c3788b2ed2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <memory> | |
#include <cassert> | |
#include <Windows.h> | |
struct FileHandle | |
{ | |
::HANDLE fileHandle; | |
//implicit | |
FileHandle(::HANDLE h) noexcept | |
: fileHandle{h} | |
{} | |
//implicit | |
FileHandle(std::nullptr_t = nullptr) noexcept | |
: FileHandle{ INVALID_HANDLE_VALUE } | |
{} | |
operator ::HANDLE() noexcept { return fileHandle; } | |
explicit operator bool() noexcept { return fileHandle != INVALID_HANDLE_VALUE; } | |
}; | |
bool operator== (FileHandle lhs, FileHandle rhs) noexcept | |
{ | |
return lhs.fileHandle == rhs.fileHandle; | |
} | |
bool operator!= (FileHandle lhs, FileHandle rhs) noexcept | |
{ | |
return !(lhs == rhs); | |
} | |
struct FileCloser | |
{ | |
using pointer = FileHandle; | |
void operator()(pointer p) const noexcept | |
{ | |
(void)::CloseHandle(p.fileHandle); | |
} | |
}; | |
using UniqueFile = std::unique_ptr<void, FileCloser>; | |
struct LocalMemoryDeleter | |
{ | |
void operator()(void* p) const noexcept | |
{ | |
(void)::LocalFree(p); | |
} | |
}; | |
using UniqueLocalMemory = std::unique_ptr<void, LocalMemoryDeleter>; | |
int main() | |
{ | |
{ | |
UniqueFile f; | |
assert(f.get().fileHandle == INVALID_HANDLE_VALUE); | |
f.reset(::CreateFile(LR"(.\Bar.txt)", GENERIC_WRITE, {}, {}, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, {})); | |
if (f) | |
{ | |
const unsigned char buffer[] = "hello"; | |
::WriteFile(f.get(), buffer, sizeof(buffer), {}, {}); | |
} | |
} | |
{ | |
const auto h = UniqueLocalMemory{ ::LocalAlloc(LMEM_FIXED, 20) }; | |
*static_cast<int*>(h.get()) = 233; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment