Boost logo

Boost :

From: Marshall Clow (mclow.lists_at_[hidden])
Date: 2022-05-14 17:28:43


> On May 14, 2022, at 12:45 AM, Rainer Deyke via Boost <boost_at_[hidden]> wrote:
>
> On 14.05.22 00:42, Marshall Clow via Boost wrote:
>>> On May 13, 2022, at 3:19 PM, Peter Dimov via Boost <boost_at_[hidden]> wrote:
>>>
>>> Marshall Clow wrote:
>>>> On May 13, 2022, at 12:29 PM, Rainer Deyke via Boost
>>>> <boost_at_[hidden]> wrote:
>>>>> That's an issue with views in general, not just cstring_view.
>>>>>
>>>>> std::string s = "hello";
>>>>> string_view sv = s;
>>>>> assert(sv.size() == 5);
>>>>> s += "!";
>>>>> assert(sv.size() == 5); // boom
>>>>
>>>> I don’t see the problem here (and when I run the code I get no error - after
>>>> adding the missing ’std::').
>>>>
>>>> No assertion failure; no undefined behavior (unlike the cstring_view example)
>>>
>>> Only because "hello!" fits into the small buffer, I suspect. If `s` reallocates,
>>> `sv` would be left dangling.
>> Agreed.
>> But even if the string *did* reallocate, the call "assert(sv.size() == 5)” is still valid and well defined.
>
> No it's not. sv.size() works by subtracting pointers, and it's only
> legal to subtract two pointers if they point into the same memory
> region. Which sv.begin() and sv.end() no longer do if s reallocates.
> It's subtle, but it's definitely undefined behavior.

Um, no. string_view::size() *could* work by subtracting two pointers, but it’s certainly not *required* to do so.

From the implementation of boost::string_view:

        BOOST_CONSTEXPR size_type size() const BOOST_NOEXCEPT { return len_; }

From the implementation od libc++’s string_view:

    _LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
    size_type size() const _NOEXCEPT { return __size; }

From the implementation of libstdc++’s string_view:

      constexpr size_type
      size() const noexcept
      { return this->_M_len; }

— Marshall


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk