std::basic_string<CharT,Traits,Allocator>::operator basic_string_view - cppreference.com

From cppreference.com

operatorstd::basic_string_view<CharT,Traits>()constnoexcept;(since C++17)
(constexpr since C++20)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.

Notes

It is the programmer's responsibility to ensure that the resulting string view does not outlive the string.

std::stringget_string();intf(std::string_viewsv);intx=f(get_string());// OKstd::string_viewsv=get_string();// Bad: holds a dangling pointerExample

Run this code

#include<iostream>#include<string>#include<string_view>voidshow_wstring_size(std::wstring_viewwcstr_v){std::cout<<wcstr_v.size()<<" code points\n";}intmain(){std::stringcppstr="ラーメン";// narrow stringstd::wstringwcstr=L"ラーメン";// wide string// Implicit conversion from string to string_view// via std::string::operator string_view:std::string_viewcppstr_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

constructs a basic_string_view
(public member function of std::basic_string_view<CharT,Traits>)

[edit]