According to this article the type serves to represent sizes in bytes of objects
Most correct.
The answers (up to the time of posting this one) are mistaken when they say that size_t
is equivalent to the primitive unsigned int
.
First, the relevant paragraph of the standardisation is the following:
[support.types.layout]/3
The type size_t
is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any Object ([expr.sizeof]).
The emphases (mine) clearly say: size_t
is an entire type without signal. In other words, size_t
may well be equivalent to uint8_t
, and may also be equivalent to uint64_t
, or other types of similar characteristic. Therefore, size_t
is not guaranteed to be equivalent to unsigned int
. It’s allowed, yes, but it’s different than being guaranteed.
Back to the question:
[...] but I always see in books and codes using the size_t type in several places that do not represent sizes.
size_t
is usually used to index arrangements (arrays) and count loops (loops). Why? Let’s use an example: when using a different type, such as unsigned int
, to index an array, it is possible that the indexing operation will fail in 64-bit systems when the index exceeds the value of UINT_MAX
, or whether the index depends on modular arithmetic to return to zero after incrementing the maximum index 1.
But still, the right kind to index containers (std::vector
, std::string
etc) is always the member ::size_type
, a typedef that is given by such containers (std::vector<int>::size_type
for example). Normally, however, ::size_type
is defined as synonymous with size_t
1. The member functions size()
containers also return a ::size_type
.
By contrast, the type ptrdiff_t
can also be used for arrangement indexing, although it is directed to the type of pointer difference value (and ::difference_type
for iterator difference) 2.
I make similar use. Generally, when I’m interacting with STL functions I use a lot
size_t
. To ensure that I am using the same type and avoid buying int and unsigned, for example.– Lucas Lima