On creating persistent objects in C + + applications

Source: Internet
Author: User
Tags arrays reflection serialization shallow copy

The persisted object is the object that has been stored in the database or saved to the local hard disk, which we call the persistent object. The following describes the persistent objects in C + +.

Persistent Objects (persistent objects) are widely used in games, distributed database systems, multimedia, and graphics applications. Currently, C + + does not directly support persistence (persistence) (but some suggestions for adding persistence and reflection (reflection) in future versions of C + +).

A persistent object can maintain its state outside the scope of the program that created it. This is an example of writing an object to a file and rebuilding it later, or transferring the object to a remote machine. Support for persistence is not as simple as it seems at first glance, the size of the same object and the memory layout may not be the same on different platforms, and the different byte order (byte ordering), or endian-ness, complicates things.

In the following I'll discuss how to implement persistence without resorting to third-party frameworks such as DCOM and CORBA. This is an effective and satisfying solution for small and portable applications.

Serialization (serialization) basics

In order for an object to persist, its state must be stored in nonvolatile storage devices. Consider an application that records and plays MP3 files, each single as an object that contains the title, record, singer, time, rate, recording date, and corresponding MP3 file, which displays the most recently played tracks in the tracking list. Your goal is to serialize the object by writing it to a file, making the MP3 object persistent, and reconstructing the objects in the next session via deserialization (deserialization).

Serialization of built-in data types

Each object is ultimately made up of built-in data members, such as int, bool, char[, and so on. Your first task is to write such a type into an output file stream (Ofstream). The application must store these values in the appropriate binary form, using the Write () and read () member functions for this purpose. Write () writes the bit pattern of the variable to a file stream, taking the address and size of a variable as an argument. The two parameters of the read () are char* and long, indicating the address and byte size of the memory buffer respectively. The following example shows how to save two integers in Ofstream:

Using reinterpret_cast<> is necessary because the first parameter type of write () is const char*, but &x and &y are int* types.

The following code reads the value just stored:

Serializing an Object

To serialize a complete object, each data member should be written to the file:

Implementing deserialize () requires some skill, because you need to assign a temporary buffer to the string. The procedure is as follows:

Performance optimization

You might be confused, why not dump the entire object into a file at once, and have to serialize each data member? In other words, can't you implement serialize () in the following way?

No, it can't be done. There are at least two problems with this approach. Typically, when a serialized object contains other objects, you cannot simply dump the object into a file and expect to rebuild a valid object from it later. In our case, the outer object contains a std::string member, and a shallow copy (shallow copy) operation archives the std::string member, but the value is time-varying, meaning that it can change every time the program is run.

Worse, since std::string does not actually contain an array of characters, but rather a pointer, it is impossible to use a shallow copy to attempt to reconstruct the original string. To overcome this problem, the program does not serialize the string object, but instead archives the characters and lengths it contains. In general, pointers, arrays, and handles should be handled in the same way.

Another problem is the design of polymorphic objects. Each Polymorphic object contains a VTPR, a hidden pointer to the virtual function address assignment table. The value of the VTPR is time-varying, and if you dump the entire Polymorphic object into a file and then forcibly add the archived data to a new object, its vptr may be invalid and cause undefined behavior. Again, the solution is to serialize and deserialize only the data members that are not time-varying. Another method is to calculate the exact offset of the vptr and not move the object when it is rebuilt from the file. Remember that the location of the vptr is related to implementation, so such code is not portable.

Summary

Although C + + does not directly support object persistence, it is not difficult to implement it manually, as long as you follow some basic guidelines: first decompose each composite object into the original data type, and then serialize the original data types. When serializing data, remember to skip the time-varying value. During deserialization, read the value just stored. There are some tricks to working with string objects, arrays, and handles: You always have to dereference them to store the values they point to. Remember to store the size of a string or array in a separate field, and hopefully it will help you with the above description.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.