C++ 现代特性:string_view、默认和删除函数及 Lambda 表达式的应用
1. 使用 string_view 替代常量字符串引用
在处理字符串时,临时对象会频繁创建,即便我们可能并未察觉。这些临时对象往往只是用于数据复制,从一个地方转移到另一个地方(例如从函数传递给调用者),这会带来性能问题,因为它们需要进行内存分配和数据复制,而这些操作是我们希望避免的。
C++17 标准引入了一个新的字符串类模板 std::basic_string_view
,它表示对字符串(即字符序列)的非拥有常量引用。
1.1 准备工作
string_view
类位于 std
命名空间的 string_view
头文件中。
1.2 操作步骤
应使用 std::string_view
来传递函数参数或从函数返回值,而非 std::string const &
,除非代码需要调用接受 std::string
参数的其他函数(这种情况下需要进行转换)。示例代码如下:
std::string_view get_filename(std::string_view str)
{
auto const pos1 {str.find_last_of('')};
auto const pos2 {str.find_last_of('.')}