std::string operator std::string_view
- since C++20
- since C++17
constexpr operator std::basic_string_view<CharT, Traits>() const noexcept;
operator std::basic_string_view<CharT, Traits>() const noexcept;
Returns a std::basic_string_view
, constructed as if by
std::basic_string_view<CharT, Traits>(data(), size())
Parametersβ
(none)
Return valueβ
A string view representing the entire contents of the string.
Complexityβ
Constant - O(1).
Exceptionsβ
(none)
Notesβ
It is the programmer's responsibility to ensure that the resulting string view does not outlive the string.
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
Exampleβ
Main.cpp
#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
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.