|
Boost : |
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2019-11-29 08:53:42
On 2019-11-29 11:12, Peter Dimov via Boost wrote:
>> and yes, you can write code that will be correct if op+= doesn't check.
>
> Maybe you can, but I apparently can't. This is what I just wrote:
>
> void my_append( fixed_string<512> & s, std::string_view s1,
> std::string_view s2 )
> {
> Â Â if( s.size() + s1.size() + s2.size() > s.max_size() ) throw
> std::length_error( "" );
>
> Â Â s += s1;
> Â Â s += s2;
> }
>
> Is this correct? (Spoiler: no.)
I think, appending N strings still requires N tests, unless you know
that the string sizes combined don't overflow.
size_t size_left = s.max_size() - s.size();
if (s1.size() > size_left) throw_length_error();
size_left -= s1.size();
if (s2.size() > size_left) throw_length_error();
Or use unsigned __int128 to calculate the combined size. Alas, it's not
universally available.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk