std::basic_...string_view(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::basic_string::operatorbasic_string_view πŸ’–

okay bestie, you're on the manual page std::basic_...string_view(3) from the C++ Standard Libary β€” yes, that's exactly how the header spells it. this one is short, iconic, and lowkey a vibe check if you fumble the lifetime. let's go. ✨

πŸŽ€ NAME πŸŽ€

  • std::basic_string::operatorbasic_string_view β€” that's the name, no cap.
  • std::basic_string::operatorbasic_string_view β€” and yep, the page lists it a second time too, so we're keeping both. πŸ’…

✨ Synopsis ✨

operator std::basic_string_view<CharT, Traits>() const       (since
C++17)
noexcept;
(constexpr since C++20)

so it's a conversion operator that gives you a std::basic_string_view. it's noexcept, and it's constexpr since C++20 β€” those labels are literally part of the synopsis, so they stay. 🫢

Returns a std::basic_string_view, constructed as if by std::basic_string_view<CharT, Traits>(data(), size()).

that's the whole move, bestie. no extra steps, no weird detours. 🌈

πŸŽ€ Parameters πŸŽ€

(none) β€” zero parameters. she takes nothing and still serves. πŸ‘‘

πŸ’– Return value πŸ’–

A string view representing the entire contents of the string.

⚠️ Notes ⚠️

⚠️ bestie, this is the important part: It is the programmer's responsibility to ensure that the resulting string view does not outlive the string.

like, this is not a drill. the page gives you this cautionary code:

std::string get_string();
int f(std::string_view sv);

int x = f(get_string()); // OK
std::string_view sv = get_string(); // Bad: holds a dangling pointer

see that second one? literally // Bad: holds a dangling pointer. the first one is // OK. that's the whole warning, and it's giving main character energy for a reason. 😭

🌈 Example 🌈

// Run this code

#include <iostream>
#include <string>
#include <string_view>

void show_wstring_size(std::wstring_view wcstr_v)
{
    std::cout << wcstr_v.size() << " code points\n";
}

int main()
{
    std::string cppstr = "ラーパン";   // narrow string
    std::wstring wcstr = L"ラーパン";  // wide string

    // Implicit conversion from string to string_view
    // via std::string::operator string_view:
    std::string_view cppstr_v = cppstr;

    std::cout << cppstr_v << '\n'
              << cppstr_v.size() << " code units\n";

    // Implicit conversion from wstring to wstring_view
    // via std::wstring::operator wstring_view:
    show_wstring_size(wcstr);
}

πŸ“ Output πŸ“

ラーパン
12 code units
4 code points

πŸ‘€ See also πŸ‘€

  • constructor β€” constructs a basic_string_view (public member function of std::basic_string_view<CharT,Traits>).

that's the whole page, bestie. source: http://cppreference.com Β· date: 2024.06.10 Β· page: std::basic_...string_view(3) β€” mwah πŸ’‹

πŸ“¦ where this page comes from