1. 简介
C++17之后才有string_view
,主要为了解决C语言常量字符串在std::string
中的拷贝问题。
即readonly
的string
。
2. 引入
2.1 隐式拷贝问题
将C常量字符串拷贝了一次
#include <iostream>
#include <string>int main()
{std::string s{ "Hello, world!" }; std::cout << s << '\n';return 0;
}
下面的程序拷贝了两次, 当然可以直接使用const std::string &str
#include <iostream>
#include <string>void printString(std::string str) // str makes a copy of its initializer
{std::cout << str << '\n';
}int main()
{std::string s{ "Hello, world!" }; // s makes a copy of its initializerprintString(s);return 0;
}
2.2 解决
对于只读的常量字符串直接声明为string_view
类型
#include <iostream>
#include <string_view>// str provides read-only access to whatever argument is passed in
void printSV(std::string_view str) // now a std::string_view
{std::cout << str << '\n';
}int main()
{std::string_view s{ "Hello, world!" }; // now a std::string_viewprintSV(s);return 0;
}
3. Ref
learn_cpp