标准容器的size_type是否保证使用默认分配器时为size_t?

7

例如:

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

无论是 cplusplus.com 还是 cppreference.com 都表示它们通常是 size_t,但除非使用自定义分配器,否则标准是否明确保证它们确实、明确地是 size_t

2个回答

7

对于STL容器而言,不支持。标准的第96张表格 [container.requirements.general] 列出了任何容器 X 的要求,已经很清楚地解释了这个问题:

enter image description here


然而,对于 basic_stringsize_type 被定义为

typedef typename allocator_traits<Allocator>::size_type size_type;

对于分配器而言,std::allocator<..>将使用size_t作为其类型。

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


0

size_type不能保证与size_t相同。

但是,默认分配器size_typesize_t,因此默认情况下也是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;

3
只有对于 basic_string 才是正确的。第23条容器不保证使用分配器的 size_type - T.C.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接