Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 551
lamefun Avatar asked Oct 17 '14 21:10

lamefun


People also ask

Is size_type same as Size_t?

size_t is defined as the type used for the size of an object and is platform dependent. container::size_type is the type that is used for the number of elements in the container and is container dependent.

What is std :: Size_t?

std::size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.

Where is std :: Size_t defined?

size_t is a base unsigned integer memsize-type defined in the standard library of C/C++ languages. This type is described in the header file stddef.

Should we use Size_t or INT?

The signed equivalent of size_t is ptrdiff_t , not int . But using int is still much better in most cases than size_t. ptrdiff_t is long on 32 and 64 bit systems. This means that you always have to convert to and from size_t whenever you interact with a std::containers, which not very beautiful.


1 Answers

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:

enter image description here


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.

like image 178
Columbo Avatar answered Oct 17 '22 21:10

Columbo