Pimpl 成语内存使用
Pimpl Idiom Memory Usage
在我的新工作场所,代码大量使用 Pimpl 惯用语,原因是为了减少编译时间。但是我有一个基本的查询——pimpl 不需要动态分配内存吗?因此,实际上我们在堆中分配了比需要更多的内存。如果它被大量使用,你最终会使用更多的内存。
那么使用它是个好主意吗?
...the reason is to reduce the compile time.
你的意思是说我猜的重新编译时间,正如Is the pImpl idiom really used in practice? ("recompilation time is really decreased, since only the source file needs to be rebuilt, but not the header, and every file that includes it")中所建议的那样。
Doesn't pimpl require dynamic allocation of memory?
不一定,它需要指针,但指针可以设置为指向任何东西,无论它是否是静态的。在 Pimpl idiom without using dynamic memory allocation.
中阅读更多内容
And if it is used a lot, you end up using more memory.
嗯,开销是由于指针(4 或 8 个字节)造成的。无论如何,数据都必须存储在某个地方,无论这个"somewhere"是否是静态的,内存都差不多。
我说的差不多了,因为如果内存是动态分配的,系统必须做一些内务处理,这会产生开销。
但是,由于您使用了 Pimpl Idiom,运行 内存不足的可能性极小。如果你这样做,那么问题就出在其他地方,如果没有那个成语,你也会内存不足。
PS:正如 juanchopanza 所说,Memory Fragmentation("when most of your memory is allocated in a large number of non-contiguous blocks, or chunks - leaving a good percentage of your total memory unallocated, but unusable for most typical scenarios") 也应该被考虑在内
在我的新工作场所,代码大量使用 Pimpl 惯用语,原因是为了减少编译时间。但是我有一个基本的查询——pimpl 不需要动态分配内存吗?因此,实际上我们在堆中分配了比需要更多的内存。如果它被大量使用,你最终会使用更多的内存。 那么使用它是个好主意吗?
...the reason is to reduce the compile time.
你的意思是说我猜的重新编译时间,正如Is the pImpl idiom really used in practice? ("recompilation time is really decreased, since only the source file needs to be rebuilt, but not the header, and every file that includes it")中所建议的那样。
Doesn't pimpl require dynamic allocation of memory?
不一定,它需要指针,但指针可以设置为指向任何东西,无论它是否是静态的。在 Pimpl idiom without using dynamic memory allocation.
中阅读更多内容And if it is used a lot, you end up using more memory.
嗯,开销是由于指针(4 或 8 个字节)造成的。无论如何,数据都必须存储在某个地方,无论这个"somewhere"是否是静态的,内存都差不多。
我说的差不多了,因为如果内存是动态分配的,系统必须做一些内务处理,这会产生开销。
但是,由于您使用了 Pimpl Idiom,运行 内存不足的可能性极小。如果你这样做,那么问题就出在其他地方,如果没有那个成语,你也会内存不足。
PS:正如 juanchopanza 所说,Memory Fragmentation("when most of your memory is allocated in a large number of non-contiguous blocks, or chunks - leaving a good percentage of your total memory unallocated, but unusable for most typical scenarios") 也应该被考虑在内