Reputation: 659
In my new workplace, the code has a heavy use of Pimpl idiom and the reason is to reduce the compile time. But I have a basic query - Doesn't pimpl require dynamic allocation of memory? So, effectively we are allocating more memory in heap than needed. And if it is used a lot, you end up using more memory. Is it a good idea to use it then?
Upvotes: 3
Views: 381
Reputation: 73366
...the reason is to reduce the compile time.
You meant to say the recompilation time I guess, as suggested in 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?
Not really, it needs pointers, but pointers can be set to point to anything, whether this is static or not. Read more in Pimpl idiom without using dynamic memory allocation.
And if it is used a lot, you end up using more memory.
Well, the overhead is due to the pointers (4 or 8 bytes). The data have to be stored somewhere in any case, and whether this "somewhere" is static or not, the memory is pretty much the same.
I said pretty much, because if the memory is dynamically allocated, the system has to do some housekeeping, which incurs in an overhead.
However, it is extremely unlikely to run out of memory because you used the Pimpl Idiom. If you do, then the problem somewhere else, and you would go out of memory without that idiom too.
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 unusable for most typical scenarios") should be taken into account too
Upvotes: 3