c++string-view

Is extending a string_view undefined behavior?


Assume we have string s and a string_view sv on some part of s such that

sv.data() + sv.size() < s.data() + s.size()

in other words, the character after the end of sv is still part of s. Is the following defined or undefined behavior?

string_view sv1 {sv.data(), sv.size()+1};

So can we extend a string_view?

From cppreference:

The behavior is undefined if [s, s+count) is not a valid range (even though the constructor may not access any of the elements of this range).

Is [sv.data(), sv.data() + sv.size() + 1) a valid range since it is part of s?


Solution

  • Yes, assuming the following:

    auto s = "The answer is: 42";
    std::string_view sv{s, 5};
    

    Then:

    std::string_view sv1{sv.data(), sv.size() + 1}; 
    

    Is a valid range. This totally goes against the C++ Core Guidelines and is likely not a great way to design your code... but yes... its valid.