【发布时间】:2014-11-19 15:25:45
【问题描述】:
我正在创建一个基于块的引擎,并且正在研究无限加载。我正在测试一些代码,但很快我就发现了一些问题。起初我使用std::unordered_map,将 xz 存储为键,将 ChunkContainer* 存储为值。我将它存储为指针(带有新的),因为它是一个如此大的对象,它不能全部存储在堆栈中。它的大小是:CHUNK_SIZE(32)^3 * WORLD_HEIGHT(8 amount of chunks in height) * 4(block bytes) = 1048576 bytes。 (而 * 225 构成了我的世界。)
然后我换成使用大数组而不是 std::unordered_map,这样我可以实现更快的读取速度。所以我需要交换加载代码。我想出了这段代码,
但我在使用此代码时遇到了一些内存泄漏问题:
for(int z = 0; z < size; z++){
temp = loadedChunkContainers[(size-1)*size + z]; //Store the last container in a temp var
for(int x = size-1; x > 0; x--){
loadedChunkContainers[x * size + z] = loadedChunkContainers[(x-1) * size + z]; //Move all containers 1 to the right
}
int cx = temp.getX() - size;
int cz = temp.getZ();
temp.move(cx, cz);//Move the container internally
loadedChunkContainers[z] = temp; //put the container back into the array, but this time on the first row
buildQueue.push_back(&loadedChunkContainers[z]);
}
temp 是一个全局变量,因为我不能在本地存储它,因为它会溢出堆栈。我也不能使用交换,因为它也会溢出堆栈。
我什至应该使用此代码吗?它有效,但首先它是一种相当缓慢的方式。是否有另一种方法可以实现最快的读取访问,同时仍然能够交换值(没有内存泄漏)?
【问题讨论】:
标签: c++ arrays memory-leaks stack-overflow