Wednesday, 15 April 2015

Simple serialization and deserialization in C++ -


I need to serialize different types of objects (but type obtained from the same class) and then base them The class indicator, which contains the derived class. For example:

  # include & lt; Iostream & gt; #to & lt include, fstream & gt; Class A {public: int a; Virtual Zero Func () {}}; Class One 1: Public A {Four S [128]; Zero Func1 (int l) {std :: cout & lt; & Lt; L & lt; & Lt; '\ N'; } Zero fun () {funk 1 (156); }}; Int main () {One * x = New One 1; X- & gt; Ceremony (); Four * y = (four *) x; Remove x; / * Std :: offream out ("test11.txt", std :: ofstream :: out | std :: ofstream :: trunc); Out.write (y, sizeof (One1)); Out.close (); Std :: ifstream in ("test11.txt", std :: ifstream :: in); Four * y1 = new four [size (solid 1)]; In.read (y1, size (forest 1)); * / A * z = (one *) y / * 1 * /; Z- & gt; Ceremony (); Return 0; }  

This code output

  156 156  

But when I repeat the comments (when I write Trying to represent a four object to a file and read from this file), output to the program 156 and assign it to z-> Ceremony (); . I have checked that the variable y has different content than y1 . Why?
What is the reason for that issue and how can I play it (perhaps using some special libraries)?

1 do not serialize derived sections by just copying bytes

By plugging in a byte array and then loading them by binary read , you can not type multicolored objects. Dump to an event of class generated derivative class for implementing virtual function with Store Points, will result in dump stored pointers in Vettel, which - compliant - should not be a valid indicator once again after running the program. Most likely a split error will arise after reaching it.

If you really want to use the easy way (directly byte reading and writing), then use the squares.

2. Do not access invalid sign recipes

The most important part of the above answer (because it will completely change your program), other things also need to be underlined. Command:

  four * y = (four *) x; Indicates the   

address of x indicates a four indicator Copy this no object, like this when you do it later:

  delete x;  

y becomes an indicator invalid when you try to write that file later:

< Pre> std :: ofstream output ("test11.txt", std :: ofstream :: out | std :: ofstream :: trunc); Out.write (y, sizeof (One1));

You can use memory that is not yours . At least not now, because you said in the specification that you do not need to call delete first.


No comments:

Post a Comment