C++ Logo


Advanced search

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

From: Lyberta <lyberta_at_[hidden]>
Date: Sat, 30 Nov 2019 19:21:00 +0000
Ville Voutilainen:> Note, though, that there is this aspect of it:
> rather than write:
> do_something(foo.at(bar));
> do_something(foo.at(bax));
> do_something(foo.at(baz));
> you can write
> if (bar >= 0 && baz <= foo.size() ) {
> do_domething(foo[bar]);
> do_something(foo[bax]);
> do_something(foo[baz]);
> }
> So, rather than looking at single-condition cases, we should remember
> to consider multi-condition ones.
What? You did 2 checks instead of 6. There's UB lurking.

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:


Means that index in unsanitized and we want bounds checking, while


means the developer promises that index is sanitized so 100% of blame
goes to developer.

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

Received on 2019-11-30 13:24:01