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

從 cppreference.com
 
 
 
 
constexpr const_pointer data() const noexcept;
(C++17 起)

返回指向底層字符數組的指針。該指針滿足範圍 [data()data() + size()) 有效,且其中的值與視圖的值對應。

目錄

[編輯] 參數

(無)

[編輯] 返回值

指向底層字符數組的指針。

[編輯] 複雜度

常數。

[編輯] 註解

不同於 std::basic_string::data() 和字符串字面量,std::basic_string_view::data() 可以返回指向不必為空終止的緩衝區的指針,例如子字符串視圖(如從 remove_suffix 獲得的)。因此,將 data() 傳遞給一個僅接收 const CharT* 並期待空終止字符串的例程通常是錯誤的。

[編輯] 示例

#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:底层字符数组为空终止
 
    char array[3] = {'B', 'a', 'r'};
    std::string_view array_v(array, sizeof array);
    // std::cout << std::strlen(array_v.data()) << '\n';
    // 错误:底层字符数组非空终止
 
    std::string str(array_v.data(), array_v.size()); // OK
    std::cout << std::strlen(str.data()) << '\n';
    // OK:std::string 的底层字符数组始终为空终止
}

輸出:

5
3

[編輯] 參閱

訪問首個字符
(公開成員函數) [編輯]
訪問最末字符
(公開成員函數) [編輯]
返回指向字符串首字符的指針
(std::basic_string<CharT,Traits,Allocator> 的公開成員函數) [編輯]