STRING还能实现写时复制等高级功能。
再贴STRING的一些其他东西成员(好像应该全是私有了,因为应该对用户透明的)
private:
// Data Members (private):
mutable _Alloc_hider _M_dataplus;
// The following storage is init'd to 0 by the linker, resulting
// (carefully) in an empty string with one reference.
static size_type _S_empty_rep_storage[(sizeof(_Rep) + sizeof(_CharT) + sizeof(size_type) - 1)/sizeof(size_type)];
这个是GCC里面STRING的实现介绍
1. String really contains _M_length + 1 characters; last is set to 0 only on call to c_str(). We avoid instantiating _CharT() where the interface does not require it.
2. _M_capacity >= _M_length
Allocated memory is always _M_capacity + (1 * sizeof(_CharT)).
3.string是个对象,因此已经对length做了重载。
public:
// Capacity:
size_type
size() const { return _M_rep()->_M_length; }
'\0' 字符很特别, 我想如果你在调试时看不到的, 并不能证明内存中就没有 '\0' 结束符, C++ 语言的创始人 Stroustrup, Bjarne, 在他的 The C++ Programming Language 一书的 5.2.2 节中有这样的话:
A string literal contains one more character than it appears to have; it is terminated by the null character '\0', with the value 0. For example:
sizeof("Bohr") == 5
The type of a string literal is "array of the appropriate number of const characters," so "Bohr" is of type const char[5].
不知道有没中文的译本, 但我想大家因该都看得懂, 如果你没有他的英文书我可以把包含这句话的第五章(ch5.pdf)文档 email 给你, 这里就不写程序证明了.
试一下不就知道了, MSDN 上说:A type that describes a specialization of the template class basic_string with elements of type char as a string.
所以我想 string 是特殊化的 char, 其内置类型是 char,MSDN上也给了个例子,不好意思,这里借用一下了,哈哈...
#include <iostream>
#include <string>
using namespace std;
void main()
{
string a="This is sample.";
char b[]="This is sample.";
if(a == b)
cout << "a and b are equal" << endl;
else
cout << "a and b are not equal" << endl;
}
Output:
a and b are equal
所以呢,是相等的。
我用size()或者length()也试了一下显示的长度都是15