C++ string到底是什么?
要回答这个问题,先要了解什么是basic_string。
看一下basic_string的声明:
template < class charT,? ? ? ? ? ? ? ? ? ? ? ? ? //定义字符串中字符的类型
? ? ? ? ? class traits = char_traits
? ? ? ? ? class Alloc = allocator
? ? ? ? ? > class basic_string;
可见,basic_string实质上是一个类模板。
再解释的稍微详细一些:
1.关于char_traits
声明:
template
作用:
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
作用:
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实例化类模板basic_string,得到一个具体的模板类,然后,将其typedef为string。
换句话说,string本质上是一个模板类,就是basic_string
ps:basic_string还有其它实例,比如说:
typedef basic_string
------------------------------分割线------------------------------
将C语言梳理一下,分布在以下10个章节中: