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)"));

这段代码的输出结果为:
image

使用string_view的好处

避免频繁拷贝

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

使用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

posted @   yuzuki_n  阅读(286)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示