std::basic_...string_view(3)
π 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 abasic_string_view(public member function ofstd::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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms