std::pair<U,V> alignment control
c++, memory-alignment, std-pair
Solution
Sorry, the `pack` pragma won't work for you in this situation. You could
#define _CRT_PACKING 1
#include <utility>
This can cause ALL SORTS of problems. One of which is that certain APIs, especially low-level ones, expect data to be aligned in a certain way. Not all of them are smart enough to deal with the situation where it's not; which could lead to unceremonious crashing.
If you really want the object to be serialised like this, handle the serialisation of `std::pair<U,V>` yourself (example only):
template<typename U, typename V>
void paircpy(char *dest, const std::pair<U, V> &pair) {
memcpy(buffer, &pair.first, sizeof(U));
memcpy(buffer + sizeof(U), &pair.second, sizeof(V));
}
You would want to handle the special case for data types that don't `memcpy` well.
What you really should do, for any serious project, is serialise objects in a portable way so that they're retrievable and elegantly handle things like floating point, different encodings for signed data types, pointers, arrays, STL containers and anything else where a simple dump of the object's memory is not possible or is insufficient.
Read the C++ FAQ and develop your own serialisation modules which are more than just dumping the in-memory representation of the object to file.
Alternatively, you can use a pre-packaged portable solution for serialising data types such as
- Boost.Serialization
- Google's Protocol Buffers
- The XDR library
- JSON or XML
Problem
I noticed one unpleasant thing that happens with std::pair when tried to save it into binary file: std::pair is aligned to a word. It might be useful in terms of processor efficiency, but requires more storage space, so I want to switch align mode to 1-byte for std::pair. My compiler is MS VC++ 2012. ``` #include <iostream> int main( ) { struct S_a { double a; size_t b; }; #pragma pack(1) struct S_wa { double a; size_t b; }; std::cout << sizeof( size_t ) << '\n'; // 4 std::cout << sizeof( double ) << '\n'; // 8 std::cout << sizeof( std::pair< size_t, size_t > ) << '\n'; // 8 std::cout << sizeof( std::pair< double, size_t > ) << '\n'; // 16 - bad std::cout << sizeof( S_wa ) << '\n'; // 12 - good std::cout << sizeof( S_a ) << '\n'; // 16 std::cout << sizeof( std::pair< double, double > ) << '\n'; // 16 } ``` I tried this, but it doesn't work: ``` #pragma pack(1) typedef std::pair< double, size_t > Q; std::cout << sizeof( Q ) << '\n'; // 16 ```