memcpy/memmove duplicate(复制数据)从源到目标。是否存在将页面从一个虚拟地址移动到另一个虚拟地址而不对源数据进行实际逐字节复制的方法?这对我来说似乎是完全可能的,但是任何操作系统实际上都允许这样做吗?动态数组是一个如此广泛和流行的概念,但通过物理复制来增长它们却是一种浪费的操作,这对我来说似乎很奇怪。当您开始谈论以千兆字节为单位的阵列大小时,它只是无法扩展(例如,想象一下将一个 100GB 的阵列增长到一个 200GB 的阵列。现在这个问题在 < 10,000 美元范围内的服务器上完全可能发生。
void* very_large_buffer = VirtualAlloc(NULL, 2GB, MEM_COMMIT);
// Populate very_large_buffer, run out of space.
// Allocate buffer twice as large, but don't actually allocate
// physical memory, just reserve the address space.
void* even_bigger_buffer = VirtualAlloc(NULL, 4GB, MEM_RESERVE);
// Remap the physical memory from very_large_buffer to even_bigger_buffer without copying
// (i.e. don't copy 2GB of data, just copy the mapping of virtual pages to physical pages)
// Does any OS provide support for an operation like this?
MoveMemory(very_large_buffer, even_bigger_buffer, 2GB)
// Now very_large_buffer no longer has any physical memory pages associated with it
VirtualFree(very_large_buffer)
最佳答案
在某种程度上,您可以使用 mremap
来做到这一点在 Linux 上。
如果可以的话,该调用会使用进程的页表进行零拷贝重新分配。。并非在所有情况下都可行(地址空间碎片,以及其他现有映射的存在本身就是一个问题)。
手册页实际上是这样说的:
mremap() changes the mapping between virtual addresses and memory pages. This can be used to implement a very efficient realloc(3).
关于c++ - 是否有任何操作系统允许将内存从一个地址移动到另一个地址而无需物理复制它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8618833/