代码之家  ›  专栏  ›  技术社区  ›  Paul J. Lucas

为什么std::string是空的?

  •  1
  • Paul J. Lucas  · 技术社区  · 15 年前

    在GNU中实现 std::string 它的 _S_empty_rep_storage 定义如下:

    template<typename _CharT, typename _Traits, typename _Alloc>
      typename basic_string<_CharT, _Traits, _Alloc>::size_type
      basic_string<_CharT, _Traits, _Alloc>::_Rep::_S_empty_rep_storage[
        (sizeof(_Rep_base) + sizeof(_CharT) + sizeof(size_type) - 1) / sizeof(size_type)
      ];
    

    为什么它被定义为 size_type 而不仅仅是 char ? 为什么不定义为:

    template<typename _CharT, typename _Traits, typename _Alloc>
      _CharT
      basic_string<_CharT, _Traits, _Alloc>::_Rep::_S_empty_rep_storage[
        sizeof(_Rep_base) + sizeof(_CharT)
      ];
    

    ?

    仅供参考:我之所以这么问是因为我正在实现自己的字符串类 (有不同的要求 std::string (不符合) 所以我想尽可能多地理解 std::string 实现了。

    2 回复  |  直到 15 年前
        1
  •  1
  •   CJBrew    15 年前

    _图表的大小可能会有所不同,尤其是如果您使用的是wchar_t而不是char。

    我意识到这只回答了部分问题。我不知道为什么Rep_base的东西是这样定义的,但总的来说,对于STL,最好不要太担心它是如何工作的;只要高兴就好了。

    因为你不太可能找到一个基本的bug。

        2
  •  1
  •   MSalters    15 年前

    对齐和舍入。这个 + sizeof(size_type) - 1) / sizeof(size_type) 零件四舍五入到下一个更高的零件编号 size_type 元素。