I have some serialization logic in which I also serialize stl datastructures. Currently I just write the size field and then each element of the structure by iterating over it. In the deserialization I read the size field and then I know when I am done reading the data structure.
No the question is how to write the size field correctly and system independent. Currently I am using the std::iterator_traits<const_iterator>::difference_type as the type to store in the file. However I am not sure, if this type is guaranteed to be system independent or if it might change, when I try to exchange files between different systems.
I had a look at this type for std::string and in this case sizeof(std::iterator_traits<std::string::const_iterator>::difference_type) returns 8 on a 64 bit machine. So I guess in this case this is just a typedef for size_t which takes up one word. I do not have a 32 bit machine available here currently so I cannot check if the size is something different on there.
Is this guaranteed by the standard to be portable, or should I use some fixed type for all data structures here to encode the length?
No, it is not portable, and yes, you should use some fixed-size type. For most applications, a 32-bit integer should be fine. Please note that, depending on your serialization code and portability requirements, you could also face byte order issues (little-endian vs. big-endian).
For more information and best practices, look at the documentation of Qt
QDataStream. The Qt people recommend to decide on a fixed-size integer type (such asqint32), then cast appropriately when serializing.