Reputation: 190
What are the downsides of using VirtualAlloc for arrays, reserving large chunk of address space, and committing pages when they are needed? For example if I know max cap for my array, I can reserve address space for it, using VirtualAlloc, and commit memory if I actually need it.
Unlike std::vector in this case, all pointers will remain valid after adding need pages to array.
I understand that this is not suitable for all arrays in program, but in the case when I need to save a pointers after array grows/resize?
Or should I just use std::deque? But with std::deque I gonna lose continues address space.
Upvotes: 0
Views: 156
Reputation: 111
VirtualAlloc is a low-level Windows API that provides lots of options for memory allocation. It can be useful in specific situations, such as when you need to share memory directly with another process. However, it is not recommended for general-purpose memory allocation.
One downside of using VirtualAlloc for arrays is that it can only allocate memory in larger chunks. This means that if your address space becomes fragmented, you have no recourse but to release and rebuild. Additionally, VirtualAlloc manages pages in the Windows virtual memory system, while HeapAlloc allocates from a specific OS heap. You are unlikely to ever need to use either of them.
In contrast, std::vector automatically manages memory allocation and reallocation for you. It can grow dynamically as needed and all pointers remain valid after adding new pages to the array.
If you need to save pointers to elements in a container after it grows or resizes, std::deque
could be a good option. Unlike std::vector
, which stores its elements in a contiguous block of memory and may need to reallocate and move its elements when it grows, std::deque
stores its elements in multiple blocks of memory. This means that when a std::deque
grows, it can add new blocks of memory without invalidating pointers to its existing elements.
However, keep in mind that std::deque has some trade-offs compared to std::vector. For example, it may not have as fast random access to its elements and may use more memory due to the overhead of managing multiple blocks of memory.
Upvotes: 0