C++ Logo

std-proposals

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: Thu, 28 Nov 2019 16:54:00 +0000
Roman Babinicz via Std-Proposals:
> draw( old_x.at(i), old_y.at(i+slowdown.at(frame)) + sky.at(i) ,
> gfxtab.at(level) )
>
> a separated out assert is more error prone, and much longer:
>
> if ( i >= old_x.size() ) throw std::overflow_error( "span bounds" );
> if ( i >= old_y.size() ) throw std::overflow_error( "span bounds" );
> if ( frame >= slowdown.size() ) throw std::overflow_error( "span
> bounds" );
> if ( i >= sky.size() ) throw std::overflow_error( "span bounds" );
> if ( level >= gfxtab.size() ) throw std::overflow_error( "span
> bounds" );
> draw( old_x[i], old_y[i+slowdown[frame]] + sky[i] , gfxtab[ level ]);

I think such code suffers from very bad class invariants. In more
traditional code you would pack your data in a struct or class and call
at() once to get a reference and then just work with that reference. In
entity component system you would rely on component existing beforehand
and, again, call at() once from untrusted input to sanitize it. Again,
use class invariants to your advantage.

At Belfast index_type became size_type so now std::span is almost sane.
Only at() is missing.


Received on 2019-11-28 10:56:50