c++17 学习笔记 string_view
如何使用string_view
使用string_view,首先需要包含头文件<string_view>
然后我们看几个例子
std::string_view extractExtension(std::string_view filename)
{
return filename.substr(filename.rfind('.'));
}
std::string filename{ R"(C:\temp\my file.exe)" };
std::cout << std::format("c++ string: {}\n", extractExtension(filename));
const char* cString{ R"(C:\temp\my file.exe)" };
std::cout << std::format("C string: {}\n", extractExtension(cString));
std::cout << std::format("Literal: {}\n", extractExtension(R"(C:\temp\my file.exe)"));
这段代码的输出结果为:

使用string_view的好处
避免频繁拷贝
string_view并不会直接拷贝一份字符串,而是再其内部记录了该字符串的地址和长度,如下图所示,在速度和内存两方面,使用string_view比string都有优势

使用string_view需要注意的事项
如前面所提到的,string_view会指向某个字符串,所以在使用时,必须保证该字符串的生命周期长于string_view,举个例子
std::string_view sv;
{
std::string temp = "hello World";
sv = temp;
}
std::cout << sv << std::endl;
这段代码中,string_view指向temp,而temp这个字符串离开其作用域后会销毁,这会产生一个未定义的行为,具体结果未知,在我的环境下,结果为:ello World。

浙公网安备 33010602011771号