zoukankan      html  css  js  c++  java
  • C++ string到底是什么

    C++ string到底是什么?

    要回答这个问题,先要了解什么是basic_string。
    看一下basic_string的声明:

    template < class charT,                          //定义字符串中字符的类型
               class traits = char_traits<charT>,    // basic_string::traits_type
               class Alloc = allocator<charT>        // basic_string::allocator_type
               > class basic_string;

    可见,basic_string实质上是一个类模板。
    再解释的稍微详细一些:

    1.关于char_traits

    声明:

    template <class charT> struct char_traits;

    作用:

    Character traits classes specify character properties and provide specific semantics for certain operations on characters and sequences of characters.(来自C++ Referencce,地址:http://www.cplusplus.com/reference/string/char_traits/)

    即:它指定了字符的属性,并且提供了作用在字符或字符序列上的某些操作的特定语义。

    2.关于allocator

    声明:

    template <class T> class allocator;//<memory>头文件下   allocator:分配器

    作用:
    Allocators are classes that define memory models to be used by some parts of the Standard Library, and most specifically, by STL containers.(来自C++ Referencce,地址:http://www.cplusplus.com/reference/memory/allocator/?kw=allocator)
    即:它定义了用于标准库的部分内容,特别是STL的内存模型。

    现在我们来看string的声明:

    typedef basic_string<char, char_traits<char>, allocator<char>> string;

    现在,我们明白了,原来是这么回事:

    用基本类型char实例化类模板basic_string,得到一个具体的模板类,然后,将其typedef为string。

    换句话说,string本质上是一个模板类,就是basic_string<char, char_traits<char>, allocator<char>>,string是对应的“简称”。 直观地理解,string的实例对象(就是说 string str;中的str)是一个char序列,但不同于char* str,stingr str带有许多封装好的针对自己的操作。

    ps:basic_string还有其它实例,比如说:

    typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t>> wstring;
  • 相关阅读:
    运算符
    JS的基本概念和数据类型
    开源基于Canal的开源增量数据订阅&消费中间件
    用AntDeploy如何更新Agent
    AntDeploy发布前端项目到IIS(脱离vs单独使用)
    截图上传录屏gif上传工具推荐
    netcore开发windows普通服务(非Web)并一键发布到服务器
    一键发布部署vs插件[AntDeploy]开源了
    基于python的Elasticsearch索引的建立和数据的上传
    浅谈闭包
  • 原文地址:https://www.cnblogs.com/zpcdbky/p/4470127.html
Copyright © 2011-2022 走看看