|
Boost : |
Subject: Re: [boost] Interest in StaticVector - fixed capacity vector
From: Dave Abrahams (dave_at_[hidden])
Date: 2011-10-15 17:03:22
on Sat Oct 15 2011, "Peter Dimov" <pdimov-AT-pdimov.com> wrote:
> Dave Abrahams wrote:
>> on Sat Oct 15 2011, "Peter Dimov" <pdimov-AT-pdimov.com> wrote:
>
>> > Yes, it's trivial to argue that logic errors should not be exceptions,
>> > but why is push_back over capacity "almost always" a logic error?
>>
>> Because for me it is like writing past the end of an array, and my
>> intuition tells me that it will be like that for many other people.
>
> It's not. Writing past the end, meaning size(), of a static_vector is
> like writing past the end of an array. push_back into a static_vector
> is like push_back into a vector.
I guess I look at this static_vector as something I might use in place
of an array when the element type was not default-constructible, in
which case, it's a lot alike.
Once you add the fixed size limit, I think vector::push_back is no
longer the right analogue unless you commonly use algorithms that
push_back into a vector, catch the exception, and continue. Otherwise
the algorithm is going to throw, which generally means it's not going to
fulfill its postconditions.
I grant you that if you have a situation where you are happy to process
only the first relatively-small, fixed, N elements of the data and
you're willing to pay a massive performance penalty should you encounter
N+1 elements, then this exception is well-suited to your job. I just
don't recall ever running into such a case. Do you?
In the standard library, the adaptive algorithms have to do something
like this but implementations don't use vector to acquire the storage in
practice... they use something that doesn't throw (e.g. malloc).
>> *Generally speaking*, in programming, if you ask for something with a
>> fixed capacity you had better not exceed it if you want your program to
>> achieve the intended result.
>
> If you use static_vector<char,...> as you would a char[], then yes, I
> guess. It's not clear what you'd gain from it though, as the whole
> point of not using char[] is to eliminate the buffer overflows.
>
>> > Heck... why is it a logic error at all, except in the trivial case in
>> > which you start with an empty static_vector<T, N> and do exactly N
>> > push_backs,
>>
>> ? That's not a logic error. You're not making sense to me.
>
> Going over capacity would be a logic error in this case,
If you do exactly N push_backs, you're not going over capacity.
> Anyway. Do you agree that the number of push_backs is typically a run
> time value?
Absolutely, 100% agreed.
-- Dave Abrahams BoostPro Computing http://www.boostpro.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk