Advices for cross platform code?

Pages: 12
LB: we seem to be talking about two different things. I thought you said you should never use basic types because they are an indeterminate size. Having re-read, that is not what you said at all, and I just completely misinterpreted. Sorry.
I said "in my opinion", so I was defending my opinion ;)
I think you misread my post, I never mentioned "std::intptr_t" and "binary files" in the same sentence.

The XX are because I didn't care to write out all the type aliases:
http://en.cppreference.com/w/cpp/header/cstdint


you mean jut using whathever alias in the cstdint lib to get a constant size across platforms?
No, I mean use the right tool for the job. Here's an example I have actually encountered: you might think that it is fine to store an index in an unsigned int, but on a platform I worked with (robot microcontroller) the size of the integer type was 16 bits, whereas the size of an index (std::size_t) is 32 bits. The conversion was implicit (and the compiler didn't warn about it) so I had to spend hours debugging to find out what had gone wrong.

Using the right tool for the job means using the correct type for storing data. An index should always be stored in a std::size_t - don't ever directly use a raw primitive type.

In other cases, I recommend std::intmax_t and std::unitmax_t until you know for a fact what the actual range you need is. Even then, don't use raw primitive types as you could again run into the scenario above where they have unexpected sizes and ranges.
Last edited on
LB wrote:
Using the right tool for the job means using the correct type for storing data. An index should always be stored in a std::size_t - don't ever directly use a raw primitive type.
+1

http://stackoverflow.com/questions/1464174/size-t-vs-intptr-t
but if I want to write a struct to a file what should I do? Write the whole thing casting the pointer to intptr_t(or whathever) or write every single member separately(again, casting to types with a known size)? I've done some research about it but I found nothing. I think that writing the whole struct would be dangerous, and the member's size can vary depending on the platform unless I caste them individually
Last edited on
You would serialize the struct to a binary format. As has been said multiple times already, you would probably find it useful to use:
- std::int8_t
- std::int16_t
- std::int32_t
- std::int64_t
- std::uint8_t
- std::uint16_t
- std::uint32_t
- std::uint64_t
In C++ it is a bad idea to think of a struct/class as 'just a bunch of data'. You are right that it is not safe to just do the whole thing in one go as is common in C.
Last edited on
thank you all for the info, it has been really helpful. Iwont bother you with more questions.
Topic archived. No new replies allowed.
Pages: 12