Skip to content

Instantly share code, notes, and snippets.

@LYP951018
Last active February 25, 2021 01:08
Show Gist options
  • Save LYP951018/491388d7644cfc6f32c876c3788b2ed2 to your computer and use it in GitHub Desktop.
Save LYP951018/491388d7644cfc6f32c876c3788b2ed2 to your computer and use it in GitHub Desktop.
#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