Memory usage idiom Pimpl

In my new workplace, the code makes heavy use of the Pimpl idiom and the reason is to reduce compile times. But I have a basic request. Does pimpl require dynamic memory allocation? Thus, we are effectively allocating more memory on the heap than necessary. And if it's used a lot, you end up using more memory. Is it a good idea to use it then?

+3


source to share


1 answer


... the reason is to reduce the compilation time.

Did you mean to say the recompilation time I am assuming as suggested in Is the pImpl idiom really used in practice? ("the recompilation time is really reduced, since only the source file needs to be rebuilt, but not the header and every file that includes it").

Does pimpl require dynamic memory allocation?

You don't really need pointers, but pointers can point to anything, whether static or not. Read more in the Pimpl idiom without using dynamic memory allocation .

And if it's used a lot, you end up using more memory.



Well, the overhead is due to pointers (4 or 8 bytes). Data has to be stored somewhere anyway, and whether it is "somewhere" static or not, memory is pretty much the same.

I said quite a lot, because if the memory is dynamically allocated, the system has to do some homework, which happens for service purposes.

However, it is highly unlikely that you ran out of memory because you were using the Pimpl Idiom. If you do this, then the problem is somewhere else and you too will lose your memory without this idiom.


PS: As juanchopanza stated, 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 unsuitable for most typical scenarios") should also be accounted for.

+2


source







All Articles