From cppreference.com
constexprconst_pointerdata()constnoexcept;(since C++17)Returns a pointer to the underlying character array. The pointer is such that the range [data(), data()+size()) is valid and the values in it correspond to the values of the view.
Return value
A pointer to the underlying character array.
Complexity
Constant.
Notes
Unlike
and string literals, std::basic_string_view::data() returns a pointer to a buffer that is not necessarily null-terminated, for example a substring view (e.g. from
). Therefore, it is typically a mistake to pass data() to a routine that takes just a constCharT* and expects a null-terminated string.
Example
Run this code
#include<cstring>#include<cwchar>#include<iostream>#include<string>#include<string_view>intmain(){std::wstring_viewwcstr_v=L"xyzzy";std::cout<<std::wcslen(wcstr_v.data())<<'\n';// OK: the underlying character array is null-terminatedchararray[3]={'B','a','r'};std::string_viewarray_v(array,sizeofarray);// std::cout << std::strlen(array_v.data()) << '\n';// error: the underlying character array is not null-terminatedstd::stringstr(array_v.data(),array_v.size());// OKstd::cout<<std::strlen(str.data())<<'\n';// OK: the underlying character array of a std::string is always null-terminated}Output:
5 3 See also
accesses the first character
(public member function)
accesses the last character
(public member function)
returns a pointer to the first character of a string
(public member function of std::basic_string<CharT,Traits,Allocator>)