• std::string_view概念原理及应用


    概念

    使用const string&作为参数是先使用字符串字面量编译器会创建一个临时字符串对象然后创建std::string。

    或者一个函数提供char*和const string&参数的两个版本函数,不是优雅的解决方案。

    于是需要一个只使用内存不维护内存的类。

    原理

    在visual studio 2019中查看std::string_view的源码。

    using string_view = basic_string_view;

    std::string_view构造时只使用内存,没有析构函数。

    1. constexpr basic_string_view(
    2. _In_reads_(_Count) const const_pointer _Cts, const size_type _Count) noexcept // strengthened
    3. : _Mydata(_Cts), _Mysize(_Count) {
    4. #if _CONTAINER_DEBUG_LEVEL > 0
    5. _STL_VERIFY(_Count == 0 || _Cts, "non-zero size null string_view");
    6. #endif // _CONTAINER_DEBUG_LEVEL > 0
    7. }

    使用内存:

    1. _NODISCARD constexpr const_iterator begin() const noexcept {
    2. #if _ITERATOR_DEBUG_LEVEL >= 1
    3. return const_iterator(_Mydata, _Mysize, 0);
    4. #else // ^^^ _ITERATOR_DEBUG_LEVEL >= 1 ^^^ // vvv _ITERATOR_DEBUG_LEVEL == 0 vvv
    5. return const_iterator(_Mydata);
    6. #endif // _ITERATOR_DEBUG_LEVEL
    7. }

    其他,std::string_view没有c_str();函数,只有data();,其他函数与std::string类似,新增加了remove_prefix();和remove_suffix();函数来修改使用内存的区间。

    1. constexpr void remove_prefix(const size_type _Count) noexcept /* strengthened */ {
    2. #if _CONTAINER_DEBUG_LEVEL > 0
    3. _STL_VERIFY(_Mysize >= _Count, "cannot remove prefix longer than total size");
    4. #endif // _CONTAINER_DEBUG_LEVEL > 0
    5. _Mydata += _Count;
    6. _Mysize -= _Count;
    7. }
    8. constexpr void remove_suffix(const size_type _Count) noexcept /* strengthened */ {
    9. #if _CONTAINER_DEBUG_LEVEL > 0
    10. _STL_VERIFY(_Mysize >= _Count, "cannot remove suffix longer than total size");
    11. #endif // _CONTAINER_DEBUG_LEVEL > 0
    12. _Mysize -= _Count;
    13. }

    应用

    1. #include
    2. #include "string_view"
    3. using namespace std;
    4. void main() {
    5. const char* p = "aaa";
    6. std::string_view sv(p,strlen(p));
    7. cout << sv.data() << endl;
    8. }

    参考:

    《c++20高级编程第5版》

  • 相关阅读:
    ChatGPT:深度学习和机器学习的知识桥梁
    ssrf学习笔记总结
    大规模 IoT 边缘容器集群管理的几种架构-6-个人体验及推荐
    SpreadJS V15.0 Update2 新特性一览
    java基于springboot +vue的图书馆图书借阅系统
    使用多线程实现批处理过程
    【神经网络】Python基于numpy灵活定义神经网络结构的方法
    CSDN21天学习挑战赛 - 第六篇打卡文章
    Android基础开发-选择图片,发送彩信
    Docker搭建Redis集群
  • 原文地址:https://blog.csdn.net/crazyeveryday/article/details/133963603