命名空间
变体
操作

std::basic_string_view<CharT,Traits>::data

来自 cppreference.cn
 
 
 
 
constexpr const_pointer data() const noexcept;
(自 C++17 起)

返回指向底层字符数组的指针。该指针使得范围 [data()data() + size()) 有效,并且其中的值对应于视图的值。

内容

[edit] 参数

(无)

[edit] 返回值

指向底层字符数组的指针。

[edit] 复杂度

常数时间复杂度。

[edit] 注意事项

std::basic_string::data() 和字符串字面量不同,std::basic_string_view::data() 返回的指针指向的缓冲区不一定是空字符结尾的,例如子字符串视图(例如来自 remove_suffix)。因此,通常将 data() 传递给仅接受 const CharT* 并期望空字符结尾字符串的例程是错误的。

[edit] 示例

#include <cstring>
#include <cwchar>
#include <iostream>
#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

[edit] 参见

访问首字符
(公共成员函数) [编辑]
访问尾字符
(公共成员函数) [编辑]
返回指向字符串首字符的指针
(std::basic_string<CharT,Traits,Allocator> 的公共成员函数) [编辑]