Domanda

From the peeks I've made into boost and libstdc++, the libraries usually make use of std::size_t and std::ssize_t whenever the upper/lower limit of an unsigned/signed index is not known in advance. My question is: Why not rather use uintmax_t from <cstdint> instead of std::size_t and intmax_t instead of std::ssize_t?

È stato utile?

Soluzione 2

The C++11 standard (section 18.2) says:

(5). The type ptrdiff_t is an implementation-defined signed integer type that can hold the difference of two subscripts in an array object....

(6). The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.

(7). [Note: It is recommended that implementations choose types for ptrdiff_t and size_t whose integer conversion ranks (4.13) are no greater than that of signed long int unless a larger size is necessary to contain all the possible values. —end note]

From this we see that:

size_t is specifically for byte-sizes of objects, and its companion ptrdiff_t is specifically for math with array indices. uintmax_t, on the other hand, is the largest unsigned integral type.

Depending on the platform uintmax_t could be larger than size_t.

We also know that:

sizeof returns a size_t, and the STL container size_types are typically identical to size_t, so it makes sense to use size_t in code that deals with sizeof or STL containers.

Now mix in the fact the <cstdint> is new-ish to C++, and I think it's pretty clear why established libraries like Boost have been using size_t.

Altri suggerimenti

The former are part of the C++ standard, the latter are not. More precisely, the cstdint header was only recently introduced (in C++11). The reason for this is that stdint.h itself is part of C99, which is newer than C++98.

Because the size_t types are intended to describe the sizes of things. Using them for sizes is more descriptive than uint_t.

Also, it might be possible for an architecture to be limited to smaller sizes of things so size_t might not always be the biggest integer type. Although I think that would be a bit weird.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top