为什么sizeof(std :: string)只有八个字节?

时间:2016-01-01 22:04:38

标签: c++

为什么std::string的尺寸由sizeof(std::string)确定,产量为8? 我认为它应该超过8,因为它必须在我的计算机上有intsizeof(int) == 8)数据成员才能在O中提供std::string::length()std::string::size() (1)并且可能是char*个字符。

2 个答案:

答案 0 :(得分:32)

C ++标准未指定std::string的实现。它只描述了类的行为。但是,我希望课堂上有不止一个指针的信息。特别是:

  • 指向实际字符串的指针。
  • 可用尺寸。
  • 使用的实际尺寸。

它当然可以将所有这些存储在动态分配的位置,因此占用的空间与[{1}} [在大多数架构中]完全相同。

实际上看看我的Linux机器附带的C ++标题,当你看一下(根据评论,这是“pre-C ++ 11”,实现是非常清楚的,但我认为这两种方式大致具有代表性):

char*

然后按照:

  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; }; 的简单指针,隐藏在几层getter中,并且有点像...

答案 1 :(得分:21)

因为std::string存储的所有实现都是指向存储所有数据的堆的指针。