【发布时间】:2013-07-05 00:02:39
【问题描述】:
我需要使用 VirtualAlloc/VirtualAllocEx 做什么?
一个例子,我发现的一个案例 - 如果我分配了 4 GB 的虚拟内存,那么如果我不使用所有这些,那么我不会花费物理内存,如果我调整我的数组大小,我 不需要重新分配和复制旧数据到新数组。
struct T_custom_allocator; // which using VirtualAllocEx()
std::vector<int, T_custom_allocator> vec;
vec.reserve(4*1024*1024*1024); // allocated virtual memory (physical memory is not used)
vec.resize(16384); // allocated 16KB of physical memory
// ...
vec.resize(32768); // allocated 32KB of physical memory
// (no need to copy of first 16 KB of data)
如果我使用标准分配器,我在调整大小时需要复制数据:
std::vector<int> vec;
vec.resize(16384); // allocated 16KB of physical memory
// ...
vec.resize(32768); // allocated 32KB of physical memory
// and need to copy of first 16 KB of data
或者使用标准分配器,我必须花费 4GB 物理内存:
std::vector<int> vec;
vec.reserve(4*1024*1024*1024); // allocated 4GB of physical memory
vec.resize(16384); // no need to do, except changing a local variable of size
// ...
vec.resize(32768); // no need to do, except changing a local variable of size
但是,为什么这比 realloc() 更好? http://www.cplusplus.com/reference/cstdlib/realloc/
还有其他使用 VirtualAlloc[Ex] 的情况吗?
【问题讨论】:
标签: c++ winapi virtualalloc