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

标签 c++

为什么 std::string 的大小,由 sizeof(std::string) 决定,产生 8
我认为它应该超过 8 因为它必须有一个 int (sizeof(int) == 8 在我的机器上)数据成员用于在 O(1) 中给出 std::string::length()std::string::size() 可能还有一个 char* 用于字符。

最佳答案

std::string 的实现没有被 C++ 标准指定。它只描述类的行为。但是,我希望类中包含不止一个指针的信息。特别是:

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

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

事实上,看看我的 Linux 机器附带的 C++ 头文件,当你看时,实现是非常清楚的(根据评论,它是“pre-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 的简单指针,隐藏在几层 getter 和一些强制转换中......

关于c++ - 为什么 sizeof(std::string) 只有八个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34560502/

相关文章:

c++ - 错误 : no matching function for call to 'variable'

c++ - 为什么这个模板变量会导致编译器警告?

c++ - 在 C++ 中使用 TCP 套接字进行远程客户端和服务器通信

c++ - 在 Windows 启动时加载应用程序

c++ - 子类化 std::thread 时的潜在竞争

c++ - 使用 std::stringstream 转换为字符串在空格处失败

c++ - 双向链表节点的下一个是私有(private)的

c++ - C++中的隐式类型转换字母

C++,重载 std::swap,编译器错误,VS 2010

c++ - 为什么 virtual 关键字会增加派生类的大小?