Debian Codegraph @

examples/storing_objects.cc

raw
1 //
2 // The following program illustrates usage of the archive I/O
3 // in the "geners" package with classes adapted to be compatible
4 // with this I/O facility. Please read the comments in the
5 // "SimpleSerializable1.hh" header for more details.
6 //
7 #include <cassert>
8
9 #include "geners/StringArchive.hh"
10 #include "geners/Record.hh"
11 #include "geners/Reference.hh"
12
13 #include "SimpleSerializable1.hh"
14 #include "SimpleSerializable2.hh"
15
16 using namespace gs;
17
18 int main(int, char**)
19 {
20 // The archive to use
21 StringArchive ar;
22
23 // The objects which we want to store in the archive
24 const SimpleSerializable1 s1(42);
25 const SimpleSerializable2 s2(1.2345);
26
27 // Store the objects in the archive
28 ar << Record(s1, "First object", "Top")
29 << Record(s2, "Second object", "Top");
30
31 // Read the objects back using optimal I/O mechanisms: restore
32 // the object on the stack for a class which implements the
33 // "restore" method, and make an object on the heap for a class
34 // which implements the "read" method.
35 SimpleSerializable1 s1_2;
36 Reference<SimpleSerializable1>(ar, "First object", "Top").restore(0,&s1_2);
37 assert(s1 == s1_2);
38
39 CPP11_auto_ptr<SimpleSerializable2> s2_2 = Reference<SimpleSerializable2>(
40 ar, "Second object", "Top").get(0);
41 assert(s2 == *s2_2);
42
43 // It is possible to use the "get" function of the archive reference
44 // with a class that has the "restore" method and the default constructor.
45 // This looses some efficiency because operator "new" is usually slower
46 // than placing an object on the stack.
47 CPP11_auto_ptr<SimpleSerializable1> s1_3 = Reference<SimpleSerializable1>(
48 ar, "First object", "Top").get(0);
49 assert(s1 == *s1_3);
50
51 // With some loss of efficiency, it is also possible to use the "restore"
52 // method of the reference with a class that has the "read" method and
53 // the assignment operator. An extra copy of the object will be made
54 // internally.
55 SimpleSerializable2 s2_3(5.678);
56 Reference<SimpleSerializable2>(ar, "Second object", "Top").restore(0,&s2_3);
57 assert(s2 == s2_3);
58
59 // We are done
60 return 0;
61 }