c++ std::string_view

std::string_view系C++17标准发布后新增的内容。

C++17中我们可以使用std::string_view来获取一个字符串的视图,字符串视图并不真正的创建或者拷贝字符串,而只是拥有一个字符串的查看功能。std::string_view比std::string的性能要高很多,因为每个std::string都独自拥有一份字符串的拷贝,而std::string_view只是记录了自己对应的字符串的指针和偏移位置。当我们在只是查看字符串的函数中可以直接使用std::string_view来代替

std::string_view记录了对应的字符串指针和偏移位置,无需管理内存,相对std::string拥有一份字符串拷贝,如字符串查找和拷贝,效率更高。

复制代码
#include <iostream>
#include <string>
#include <string_view>
 
int main()
{
 
    const char* cstr = "yangxunwu";
    std::string_view stringView1(cstr);
    std::string_view stringView2(cstr, 4);
    std::cout << "stringView1: " << stringView1 << ", stringView2: " << stringView2 << std::endl;
 
    std::string str = "yangxunwu";
    std::string_view stringView3(str.c_str());
    std::string_view stringView4(str.c_str(), 4);
    std::cout << "stringView3: " << stringView1 << ", stringView4: " << stringView2 << std::endl;
}
复制代码

输出:

stringView1: yangxunwu, stringView2: yang
stringView3: yangxunwu, stringView4: yang

你可以把原始的字符串当作一条马路,而我们是在马路边的一个房子里,我们只能通过房间的窗户来观察外面的马路。这个房子就是std::string_view,你只能看到马路上的车和行人,但是你无法去修改他们,可以理解你对这个马路是只读的。正是这样std::string_view比std::string会快上很多。

之所以这样时因为std::string在进行操作时会重新分配内存,生成一个对应的std::string副本,大量的new操作。而std::string_view操作,从头到尾其实只有一个字符串数据,其它皆为视图。这也是需要注意的地方,因为std::string_view是原始字符串的视图,如果在查看std::string_view的同时修改了字符串,或者字符串被消毁,那么将是未定义的行为(od)。

复制代码
#include <iostream>
#include <string>
#include <string_view>
 
std::string_view GetStringView()
{
    std::string name = "xunwu";
 
    return std::string_view(name);  //离开作用域时,name已经被回收销毁
}
 
int main()
{
    std::string_view stringView = GetStringView();
    std::cout << stringView << std::endl;
}
复制代码

输出 烫烫

 

转载:https://www.cnblogs.com/yangxunwu1992/p/14018837.html

posted @   _Explosion!  阅读(172)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示