【问题标题】:Is std::container::size_type guaranteed to be size_t for standard containers with default allocator?对于具有默认分配器的标准容器,std::container::size_type 是否保证为 size_t?
【发布时间】:2014-12-13 13:19:58
【问题描述】:

喜欢:

  • std::string<T>::size_type
  • std::list<T>::size_type
  • std::map<T>::size_type
  • std::vector<T>::size_type

cplusplus.comcppreference.com 都表示它们通常是 size_t,但除非使用自定义分配器,否则它们是否真的、明确地保证标准为 size_t

【问题讨论】:

    标签: c++ stl portability


    【解决方案1】:

    对于 STL 容器 - 不。 [container.requirements.general] 中的标准表 96 列出了任何容器 X 的容器要求,解释得很清楚:


    但是,对于basic_stringsize_type 被定义为

    typedef typename allocator_traits<Allocator>::size_type size_type;
    

    作为分配器的size_t 又是std::allocator&lt;..&gt;

    此外,根据 [array.overview]/3,std::array 使用 size_t 作为 size_type

    【讨论】:

      【解决方案2】:

      size_type 不保证是size_t

      但是 default allocator size_type 是,所以默认是size_t

      从标准 20.6.9

      template <class T> class allocator {
      public:
      typedef size_t size_type;
      typedef ptrdiff_t difference_type;
      ....
      

      容器的size_type来源于分配器:

      typedef typename allocator_traits<Allocator>::size_type size_type;
      

      【讨论】:

      • 这仅适用于basic_string。第 23 条容器不保证使用分配器的size_type
      猜你喜欢
      • 2018-02-15
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多