string_view is a borrowed range but it can still dangle

I thought iterators to borrowed ranges could not dangle! Because of it being a borrowed_range???

The text says

iterators can still dangle when the underlying character sequence is no longer there...

if you have a borrowed iterator that refers to a range, the iterator is safe to use and does not dangle even when the range is destroyed...

It seems to conflict...
Last edited on
cppreference wrote:
The concept borrowed_range defines the requirements of a range such that a function can take it by value and return iterators obtained from it without danger of dangling.

std::string s = "abc";
std::string_view::iterator svi;
	std::string_view sv = s;
	svi = sv.begin();
std::cout << *svi;

svi is not dangling on line 7 despite that sv has been destroyed.

However, if the code was rewritten in such a way that s was destroyed before svi then it would be dangling.
Last edited on
Registered users can post here. Sign in or register to post.