C++ Logo


Advanced search

Re: function at() for span<> that throws exception on out-of-range, like vector and array ::at()

From: Miguel Ojeda <miguel.ojeda.sandonis_at_[hidden]>
Date: Sat, 30 Nov 2019 20:29:59 +0100
On Sat, Nov 30, 2019 at 8:21 PM Lyberta via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> What? You did 2 checks instead of 6. There's UB lurking.

I assume Ville implied a sequence of indexes, i.e. bar < bax < baz.

> Anyway. My fundamental opinion is that operator[] should do bounds
> checking while unsafe_at() should not because it is clearly named unsafe.
> So a code like this:
> buffer[index];
> Means that index in unsanitized and we want bounds checking, while
> buffer.unsafe_at(index);
> means the developer promises that index is sanitized so 100% of blame
> goes to developer.

I would agree, but then `operator[]` would behave differently than C
arrays, which I guess it was why it was done that way originally.

> Right now if I see buffer[index] and index is not sanitized, then 10% of
> blame goes to developer and 90% to ISO C++ committee. :P

Note that `index` may be sanitized and yet wrong due to a logic bug.
My point is that sometimes you may see `operator[]` and be completely
correct, and others you may see code trying to sanitize inputs and
still be totally wrong in the end.


Received on 2019-11-30 13:32:33