简体   繁体   中英

size_t template parameter in std::array

The std::array template parameters are template < class T, size_t N > class array; where N stands for the number of elements in the array.

My doubt is why is the type std::size_t ? Isn't std::size_t an alias for the size of an object/pointer in bytes. std::size_t

Why is it used to denote the number of elements in std::array here?

The type std::size_t is defined to be a numeric type that can represent the size of the largest possible object (say, N bytes).

The largest object could be an array, and the array with the most possible objects is therefore an array of N char s.

So, std::size_t makes sense for array indexes and dimensions too .

You should stick to this convention as much as possible, because otherwise you potentially introduce bugs:

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, eg 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic ( cppref )

We could have had a std::index_t instead, but it would have been the same as std::size_t , so that's pointless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM