std::string_view data() 方法
- 自 C++17 起
// Const version only
constexpr const_pointer data() const noexcept;
返回指向底层字符数组的指针。
该指针使得范围 [ data(); data() + size() ) 有效,且其中的值与视图的值相对应。
参数
(无)
返回值
指向底层字符存储的指针。
复杂度
常数 - O(1)。
备注
注意
与 std::string::data()
和字符串字面量不同,std::string_view::data()
返回的指针指向的缓冲区不一定以空字符结尾,例如子字符串视图(如通过 remove_suffix()
获得)。
因此,将 data()
传递给只接受 const CharT*
并期望空字符结尾字符串的例程通常是一个错误。
示例
Main.cpp
#include <iostream>
#include <cstring>
#include <cwchar>
#include <string>
#include <string_view>
int main()
{
std::wstring_view wcstr_v = L"xyzzy";
std::cout << std::wcslen(wcstr_v.data()) << '\n';
// OK: the underlying character array is null-terminated
char array[3] = {'B', 'a', 'r'};
std::string_view array_v(array, sizeof array);
// std::cout << std::strlen(array_v.data()) << '\n';
// error: the underlying character array is not null-terminated
std::string str(array_v.data(), array_v.size()); // OK
std::cout << std::strlen(str.data()) << '\n';
// OK: the underlying character array of a std::string is always null-terminated
}
输出
5
3