实施std::string
C++ 标准没有指定。它仅描述类的行为。然而,我希望类中会有不止一个指针的信息价值。尤其:
- 指向实际字符串的指针。
- 尺寸可用。
- 实际使用的尺寸。
当然,它可以将所有这些存储在动态分配的位置中,因此占用与char*
[在大多数架构中]。
事实上,查看我的 Linux 机器附带的 C++ 头文件,当您查看时,其实现非常清晰(根据评论,它是“C++11 之前的版本”,但我认为无论哪种方式都大致具有代表性):
size_type
length() const _GLIBCXX_NOEXCEPT
{ return _M_rep()->_M_length; }
然后按照以下步骤操作:
_Rep*
_M_rep() const _GLIBCXX_NOEXCEPT
{ return &((reinterpret_cast<_Rep*> (_M_data()))[-1]); }
这又导致:
_CharT*
_M_data() const _GLIBCXX_NOEXCEPT
{ return _M_dataplus._M_p; }
这导致
// Data Members (private):
mutable _Alloc_hider _M_dataplus;
然后我们就可以:
struct _Alloc_hider : _Alloc
{
_Alloc_hider(_CharT* __dat, const _Alloc& __a) _GLIBCXX_NOEXCEPT
: _Alloc(__a), _M_p(__dat) { }
_CharT* _M_p; // The actual data.
};
有关字符串的实际数据是:
struct _Rep_base
{
size_type _M_length;
size_type _M_capacity;
_Atomic_word _M_refcount;
};
所以,这都是一个简单的指针,称为_M_p
隐藏在几层吸气剂和一些铸造里面......