On Feb 23, 2:15 am, Mark <i...@dontgetlotsofspamanymore.invalid>
wrote:
> You could locate the correct location in the byte stream and then cast
> it to the pointer of the correct type.
As explained else-thread, if I understand your suggestion correctly,
this will lead to undefined behavior from violating the strict
aliasing rule, and potentially lead to undefined behavior from
violating alignment requirements. See Ben Kaufman's post for something
that works if you're willing to assume a certain int size.
If you know the serialization will be temporary, and only to this
computer, then you can "hack it" (without undefined behavior) with
something like:
#include <fstream>
using namespace std;
int main()
{
//read from file
ifstream fin("a", ios::binary);
char buf[sizeof(int)];
fin.read(buf, sizeof buf);
int x;
char* c2 = reinterpret_cast<char*>(&x);
for (int i=0; i<sizeof(int); ++i)
c2[i] = buf[i];
//write to file
ofstream fout("a", ios::binary);
int y = 2;
fout.write(reinterpret_cast<char*>(&y), sizeof y);
}
Remember, in C and C++ you are allowed to read from or write to any
POD object through a char lvalue or an unsigned char lvalue. Do not
think in terms of the allowed casting. Think instead of the type of
the expression (lvalue) used to access the object. You can access an
int object through a char lvalue, but you cannot access a char object
through an int lvalue. You should probably look up the actual rules -
they're somewhat arcane and involved, and I've left out a lot of
details. Offhand, I again suggest:
http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-fstrict_002daliasing-849
http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html
If you know the serialization will be used between computers, and you
want to write portable code, then you need to use a portable
serialization scheme. See Boost's serialization library as starting
place, and see google as well.