c++ - std::pair<U,V> alignment control -


i noticed 1 unpleasant thing happens std::pair when tried save binary file: std::pair aligned word. might useful in terms of processor efficiency, requires more storage space, want switch align mode 1-byte std::pair. compiler 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 -     std::cout << sizeof( s_a ) << '\n';                             // 16     std::cout << sizeof( std::pair< double, double > ) << '\n';     // 16 } 

i tried this, doesn't work:

#pragma pack(1)     typedef std::pair< double, size_t > q;      std::cout << sizeof( q ) << '\n';                               // 16 

sorry, pack pragma won't work in situation.

#define _crt_packing 1 #include <utility> 

this can cause sorts of problems. 1 of apis, low-level ones, expect data aligned in way. not of them smart enough deal situation it's not; lead unceremonious crashing.

if want object serialised this, handle serialisation of std::pair<u,v> (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 want handle special case data types don't memcpy well.

what should do, serious project, serialise objects in portable way they're retrievable , elegantly handle things floating point, different encodings signed data types, pointers, arrays, stl containers , else simple dump of object's memory not possible or insufficient.

read c++ faq , develop own serialisation modules more dumping in-memory representation of object file.

alternatively, can use pre-packaged portable solution serialising data types such as


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -