vector with constant size
I am looking for a C++ data type similar to std::vector
but without the overhead related to dynamic resizing. The size of the container will remain constant over its lifetime. I considered using boost::array
, however, that is not appropriate because it requires the size of the array 开发者_StackOverflow中文版to be known at compile time, which is not the case in my situation.
Measure if the dynamic resizing has really any performance impact before using anything non-standard.
Tip: With vector.reserve there will never be any array-reallocation.
There's no overhead in reallocation if you don't reallocate std::vector. So either:
- construct the std::vector with a known size ahead (
std::vector x(100)
) - call reserve(n) after construction to make sure that at least n elements can be pushed into the vector before reallocation occurs.
The overhead induced by dynamic resizing capability of std::vector
is virtually non-existent.
If you needed an array of compile-time size, looking for something more efficient than std::vector
would indeed be a good idea in many cases.
But the difference between fixed run-time size and dynamic run-time size is negligible. std::vector
is a perfect solution in this case.
I've used a template class based on ideas from STLSoft's auto_buffer
(I cobbled together my own implementation from Matthew Wilson's Imperfect C++ book along with some ideas from the STLSoft implementation). It allocates the array by default on the stack (or embedded in the class object) if it's small enough (based on a template parameter you provide). If your runtime allocation is larger than that, the array storage comes from the heap.
http://www.stlsoft.org/doc-1.9/classstlsoft_1_1auto__buffer.html
So the nice thing about this class is that for smaller small sizes, the allocation is essentially a no-op.
If the size of the array is not known at compile time, then the only option in C++ is a dynamically-allocated array. You can use a std::vector
to guarantee RAII. As others have said, the fact that std::vector
s can be resized doesn't mean that you have to resize them. Create the std::vector
with the correct size, and then don't call anything that would resize it.
精彩评论