C++17如何用std::string_view避免字符串拷贝改写为长尾?
- 内容介绍
- 文章标签
- 相关推荐
本文共计915个文字,预计阅读时间需要4分钟。
C++中std::string是日常编码中经常使用的一个类,使用起来非常方便,但也存在一些弊端。例如,如下代码,参数传递过程中发生了内存分配和内存拷贝。
cppvoid fun(const std::string& str);
C++中std::string是日常Coding中经常使用的一个类,使用起来非常方便,但是也存在一些弊端。
如下代码,参数传递的过程发生了内存分配(Memory Allocation)和内存拷贝。
void fun(const std::string& s) { std::cout << s << std::endl; } const char* ch = "hello world"; // bad way, expensive if the string is long fun(ch);
再看下面的常用的字符串截取实现:
// very long string std::string str = "lllloooonnnngggg sssstttrrriiinnnggg"; // bad way, expensive if the string is long std::cout << str.substr(15, 10) << '\n';
为了进一步的压榨程序的性能,需要移除掉这些昂贵的字符串内存分配和拷贝操作。C++17中提供了std::string_view可以帮助我们实现这一功能,该类并不持有字符串的拷贝,而是与源字符串共享其内存空间。
本文共计915个文字,预计阅读时间需要4分钟。
C++中std::string是日常编码中经常使用的一个类,使用起来非常方便,但也存在一些弊端。例如,如下代码,参数传递过程中发生了内存分配和内存拷贝。
cppvoid fun(const std::string& str);
C++中std::string是日常Coding中经常使用的一个类,使用起来非常方便,但是也存在一些弊端。
如下代码,参数传递的过程发生了内存分配(Memory Allocation)和内存拷贝。
void fun(const std::string& s) { std::cout << s << std::endl; } const char* ch = "hello world"; // bad way, expensive if the string is long fun(ch);
再看下面的常用的字符串截取实现:
// very long string std::string str = "lllloooonnnngggg sssstttrrriiinnnggg"; // bad way, expensive if the string is long std::cout << str.substr(15, 10) << '\n';
为了进一步的压榨程序的性能,需要移除掉这些昂贵的字符串内存分配和拷贝操作。C++17中提供了std::string_view可以帮助我们实现这一功能,该类并不持有字符串的拷贝,而是与源字符串共享其内存空间。

