std::basic_string_view<CharT,Traits>::data
來自 cppreference.com
< cpp | string | basic string view
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: 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
[編輯] 參閱
訪問第一個字元 (公共成員函式) | |
訪問最後一個字元 (公共成員函式) | |
返回指向字串第一個字元的指標 ( std::basic_string<CharT,Traits,Allocator> 的公共成員函式) |