1

I'm writing a set of pure virtual classes that act as interfaces. The idea is that the code implementing such interfaces could be built with a different build configuration, compiler, or even a different STL implementation to code making use of such an object via such an interface.

Plain old data like uint32_t is standardised as is double and float. (bool is not since the standard does not state its size.)

Which category does std::size_t come in? Is it purely a function of the machine architecture? For example, on a 32 bit machine, could it ever be such that sizeof(std::size_t) is not 4?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
P45 Imminent
  • 8,319
  • 4
  • 35
  • 78
  • 6
    The standard does not state the size of `double` and `float`. – R. Martinho Fernandes Sep 15 '14 at 12:54
  • I though it did *effectively* by stating that they are IEEE 32 and 64 bit floating point types. Perhaps I'll put in a `static_assert` to qualify my assumption. – P45 Imminent Sep 15 '14 at 12:55
  • The standard does not require `double` and `float` to be IEEE floating point types. If it required that then `numeric_limits::is_iec559` would be redundant because it would always be true. – Jonathan Wakely Sep 15 '14 at 12:58

2 Answers2

5

size_t is only required to be unsigned and large enough to contain the size of any object in bytes, so depending on its size is a not portable. This is covered in the draft C++ standard section 18.2 Types which says:

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

For integers if you need a specific width you need to use the types defined in cstdint header.

Note, the standard does not specify the size of float and double, they are not required to be IEEE 754 floating point numbers.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • +1 Many thanks, in particular for quoting the standard. That will make a useful program comment so keeping my boss happy. – P45 Imminent Sep 15 '14 at 12:54
2

Actually, neither double nor float have standardized sizes. In fact, the only types that do are the (u)intNN_t types, and they might not exist.

So the documentation you need is not the standard, it is the target compiler documentation.

But for the purpose of stability across compilers, compiler versions, build configurations and standard libraries, it's pretty safe to assume that on any given platform, std::size_t has a consistent size. Note, however, that 32-bit and 64-bit builds are different platforms.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157