Is `string.assign(string.data(), 5)` well-defined or UB? : <p>A coworker wanted to write this:</p>

<pre><code>std::string_view strip_whitespace(std::string_view sv);

std::string line = "hello  ";
line = strip_whitespace(line);
</code></pre>

<p>I said that returning <code>string_view</code> made me uneasy <em>a priori</em>, and furthermore, the aliasing here looked like UB to me.</p>

<p>I can say with certainty that <code>line = strip_whitespace(line)</code> in this case is equivalent to <code>line = std::string_view(line.data(), 5)</code>. I believe that will call <a href="http://eel.is/c++draft/basic.string#string.cons-itemdecl:16" rel="noreferrer"><code>string::operator=(const T&amp;) [with T=string_view]</code></a>, which is defined to be equivalent to <a href="http://eel.is/c++draft/basic.string#string.assign-itemdecl:4" rel="noreferrer"><code>line.assign(const T&amp;) [with T=string_view]</code></a>, which is defined to be equivalent to <a href="http://eel.is/c++draft/basic.string#string.assign-itemdecl:6" rel="noreferrer"><code>line.assign(line.data(), 5)</code></a>, which is defined to do this:</p>

<pre><code>Preconditions: [s, s + n) is a valid range.
Effects: Replaces the string controlled by *this with a copy of the range [s, s + n).
Returns: *this.
</code></pre>

<p>But this doesn't say what happens when there's aliasing.</p>

<p>I asked this question on the cpplang Slack yesterday and got mixed answers. Looking for super authoritative answers here, and/or empirical analysis of real library vendors' implementations.</p>

<hr>

<p><a href="https://godbolt.org/z/y_R8-9" rel="noreferrer">I wrote test cases</a> for <code>string::assign</code>, <code>vector::assign</code>, <code>deque::assign</code>, <code>list::assign</code>, and <code>forward_list::assign</code>.</p>

<ul>
<li>Libc++ makes all of these test cases work.</li>
<li>Libstdc++ makes them all work except for <code>forward_list</code>, which segfaults.</li>
<li>I don't know about MSVC's library.</li>
</ul>

<p>The segfault in libstdc++ gives me hope that this is UB; but I also see both libc++ and libstdc++ going to great effort to make this work at least in the common cases.</p>
