Is std::container::size_type guaranteed to be size_t for standard containers with default allocator?

对着背影说爱祢 提交于 2020-01-01 09:35:06

问题


Like:

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

Both cplusplus.com and cppreference.com say that they are usually size_t, but are they truly, unambiguously guaranteed by the standard to be size_t unless a custom allocator is used?


回答1:


For STL-containers - nope. Table 96 of the standard in [container.requirements.general], which lists container requirements for any container X, explains it pretty clear:


However, for basic_string, size_type is defined as

typedef typename allocator_traits<Allocator>::size_type size_type;

which in turn will be size_t for std::allocator<..> as the allocator.

Also, std::array uses size_t as size_type, according to [array.overview]/3.




回答2:


size_type isn't guaranteed to be size_t.

But the default allocator size_type is, so the default is size_t.

From the standard 20.6.9

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

The container's size_type is derived from the allocator:

typedef typename allocator_traits<Allocator>::size_type size_type;


来源:https://stackoverflow.com/questions/26433802/is-stdcontainersize-type-guaranteed-to-be-size-t-for-standard-containers-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!