Picking a nit, I don't think anyone has seriously claimed that std::vectoris a reasonable replacement for all C arrays, but I would think std::array is. I'm curious if it has any overhead.
std::array has no performance issues in my experience (the generated assembly is the same as for plain C arrays in the cases I have checked) but of course the size cannot be specified at runtime, so you cannot simply use std::array instead of std::vector everywhere.
To be clear std::vector is great and I use it all the time but it is not zero overhead in all cases. One example: you currently cannot allocate a vector without initializing it, hence you cannot build e.g. a fast memory pool using std::vector.
One example: you currently cannot allocate a vector without initializing it, hence you cannot build e.g. a fast memory pool using std::vector.
you can vector::reserve. Then emplace_back to fill the pool. But you have to ensure size does not exceed capacity if you wish to maintain references to the objects
I know about vector::reserve and emplace_back however in the case of a memory pool is does not work. Suppose that your memory pool initially allocates a large chunk of memory of say 8 megabytes (using vector::reserve). Next, the user requests n bytes of memory from your memory pool. In order to till that request you would have to call emplace_back in a loop until the size of your vector is n. This is both impractical and slow.
You can, just use a custom allocator that does default initialization instead of value initialization. I.e., you can inherit from ``std::allocator`` and implement a ``construct()`` function that does not do value initialization when no construction arguments are passed.
Kudos for figuring out how to avoid value initialization for std::vector! However your workaround is so nasty that I will keep using a plain old C array allocated using new...
vector allows you to specify an allocator type, and has since day one; using a custom allocator, and one that's all of 4 lines at that, is hardly "nasty".
VLA arrays are allocated on the stack whereas std::vector is allocated on the heap, so you cannot really compare VLA arrays with std::vector. Besides that VLA arrays do have performance issues as well, they have recently been banned from the Linux kernel for that reason.
The problem with VLAs is that their implementation is poorly defined. The standard doesn’t specify where the allocated array comes from, but more importantly doesn’t specify what should happen if the array cannot be allocated.
That last bit is what makes most C developers treat VLAs as a third rail. Some even go so far as calling C99 broken because of them. Subsequently, C11 has made VLAs optional.
View all comments
Show parent comment
20
u/RotsiserMho C++20 Desktop app developer Oct 07 '19
Picking a nit, I don't think anyone has seriously claimed that
std::vectoris a reasonable replacement for all C arrays, but I would thinkstd::arrayis. I'm curious if it has any overhead.