Reputation: 22492
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 to be known at compile time, which is not the case in my situation.
Upvotes: 11
Views: 6440
Reputation: 320461
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.
Upvotes: 4
Reputation: 20041
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.
Upvotes: 1
Reputation: 28737
There's no overhead in reallocation if you don't reallocate std::vector. So either:
std::vector x(100)
)Upvotes: 10
Reputation: 340208
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.
Upvotes: 2
Reputation: 1479
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.
Upvotes: 15