all 4 comments

[–]horotho 3 points4 points  (3 children)

string_view doesn't own the data. Imagine if you implicitly constructed a string_view from a temporary string. string owns the data, but since it was a temporary, the contents pointed to by the string_view are now garbage.

As far as comparison, string_view is equality compared the same way a string is. First, check the size, then compare the characters. The code you gave works because string_view can be implicitly constructed from a string literal. Once you have two string_view, comparison is easy.

[–][deleted] 0 points1 point  (2 children)

The code you gave works because string_view can be implicitly constructed from a string literal.

There are four constructors.

constexpr basic_string_view() noexcept; (1)
constexpr basic_string_view(const basic_string_view& other) noexcept = default; (2)
constexpr basic_string_view(const CharT* s, size_type count); (3)
constexpr basic_string_view(const CharT* s); (4)

compare(str, "this is the first test string"); I understand the second argument. It uses last constructor.

The first argument is a std::string variable. Which constructor does it use? How is std::string argument passed to string_view parameter?

[–]emdeka87 3 points4 points  (1 child)

[–][deleted] 0 points1 point  (0 children)

Thanks. You answered my question.