超值的网站建设百度app下载最新版本
概念
使用const string&作为参数是先使用字符串字面量编译器会创建一个临时字符串对象然后创建std::string。
或者一个函数提供char*和const string&参数的两个版本函数,不是优雅的解决方案。
于是需要一个只使用内存不维护内存的类。
原理
在visual studio 2019中查看std::string_view的源码。
using string_view = basic_string_view<char>;
std::string_view构造时只使用内存,没有析构函数。
constexpr basic_string_view(_In_reads_(_Count) const const_pointer _Cts, const size_type _Count) noexcept // strengthened: _Mydata(_Cts), _Mysize(_Count) {
#if _CONTAINER_DEBUG_LEVEL > 0_STL_VERIFY(_Count == 0 || _Cts, "non-zero size null string_view");
#endif // _CONTAINER_DEBUG_LEVEL > 0}
使用内存:
_NODISCARD constexpr const_iterator begin() const noexcept {
#if _ITERATOR_DEBUG_LEVEL >= 1return const_iterator(_Mydata, _Mysize, 0);
#else // ^^^ _ITERATOR_DEBUG_LEVEL >= 1 ^^^ // vvv _ITERATOR_DEBUG_LEVEL == 0 vvvreturn const_iterator(_Mydata);
#endif // _ITERATOR_DEBUG_LEVEL}
其他,std::string_view没有c_str();函数,只有data();,其他函数与std::string类似,新增加了remove_prefix();和remove_suffix();函数来修改使用内存的区间。
constexpr void remove_prefix(const size_type _Count) noexcept /* strengthened */ {
#if _CONTAINER_DEBUG_LEVEL > 0_STL_VERIFY(_Mysize >= _Count, "cannot remove prefix longer than total size");
#endif // _CONTAINER_DEBUG_LEVEL > 0_Mydata += _Count;_Mysize -= _Count;}constexpr void remove_suffix(const size_type _Count) noexcept /* strengthened */ {
#if _CONTAINER_DEBUG_LEVEL > 0_STL_VERIFY(_Mysize >= _Count, "cannot remove suffix longer than total size");
#endif // _CONTAINER_DEBUG_LEVEL > 0_Mysize -= _Count;}
应用
#include <iostream>
#include "string_view"
using namespace std;
void main() {const char* p = "aaa";std::string_view sv(p,strlen(p));cout << sv.data() << endl;
}
参考:
《c++20高级编程第5版》