string_view
string_view 是C++17所提供的用於處理只讀字符串的輕量對象。這里后綴 view 的意思是只讀的視圖。
- 通過調用 string_view 構造器可將字符串轉換為 string_view 對象。
string 可隱式轉換為 string_view。 - string_view 是只讀的輕量對象,它對所指向的字符串沒有所有權。
- string_view通常用於函數參數類型,可用來取代 const char* 和 const string&。
string_view 代替 const string&,可以避免不必要的內存分配。 - string_view的成員函數即對外接口與 string 相類似,但只包含讀取字符串內容的部分。
string_view::substr()的返回值類型是string_view,不產生新的字符串,不會進行內存分配。
string::substr()的返回值類型是string,產生新的字符串,會進行內存分配。 - string_view字面量的后綴是 sv。(string字面量的后綴是 s)
示例
#include <string>
#include <iostream>
using namespace std;
// void process(const char* sv)
// void process(const string& sv)
void process(string_view sv)
{
cout << sv << endl;
for (char ch : sv)
cout << ch;
cout << sv[2] << endl;
}
int main()
{
string_view sv = "hello"sv;
cout << sv << endl;
string_view sv2 = "hello";
cout << sv2 << endl;
string_view sv3 = "hello"s;
cout << sv3 << endl;
string_view sv4("hello", 4);
cout << sv4 << endl;
process("hello");
process("hello"s);
}
/*
hello
hello
hello
hell
hello
hellol
hello
hellol
*/
