并不是说它特别有用,但我很好奇为什么以下工作,仅仅是因为即使在文件被删除后页面仍然在内存中?在这种情况下,如果页面被换出,数据会丢失吗?
#include <iostream>
#include <memory>
#include <windows.h>
int main()
{
typedef std::unique_ptr<void, decltype(&CloseHandle)> Handle;
typedef std::unique_ptr<void, decltype(&UnmapViewOfFile)> View;
View v(nullptr, UnmapViewOfFile);
{
Handle h(CreateFile(
L"test",
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
CREATE_ALWAYS,
FILE_FLAG_DELETE_ON_CLOSE,
nullptr
), CloseHandle);
// write something so CreateFileMapping succeeds
DWORD sz;
WriteFile(h.get(), "hello world", 12, &sz, nullptr);
Handle m(CreateFileMapping(
h.get(),
nullptr,
PAGE_READWRITE,
0, 0,
nullptr
), CloseHandle);
v.reset(MapViewOfFile(
m.get(),
FILE_MAP_WRITE,
0, 0,
0
));
char c;
std::cin >> c; // File is still in folder
}
char c;
std::cin >> c; // No file!
std::cout << static_cast<char*>(v.get()); // Still writes
}