Find us on Facebook
More keeppies by alexey
Persistent C++ Objects by alexey ,  Sep 13, 2015
What is a Persistent Object?

A persistent object retains its state outside the scope of the program in which it was created. Writing an object to a file and reconstituting it later or transmitting it to a remote machine are instances of this.
To make an object persistent, you have to reserve its state in a non-volatile storage device.
How to Create a Persistent C++ Object?

There are several ways to do that:


1) Use ODB
ODB is an object-relational mapping (ORM) system for the C++ language. It allows an application developer to persist C++ objects to a relational database without having to deal with tables, columns, or SQL and without manually writing any mapping code.
There are certain limitations on C++ classes in order to make them persistent.  A default constructor is requited along with a data member id_.  Sample ODB-based persistent project (from http://www.codesynthesis.com/products/odb/doc/manual.xhtml#2  ):

class person
{
public:
  person ();

  const std::string& email () const;
  void email (const std::string&);

  const std::string& get_name () const;
  std::string& set_name ();

  unsigned short getAge () const;
  void setAge (unsigned short);

private:
  std::string email_;
  std::string name_;
  unsigned short age_;
};

#pragma db object(person)
#pragma db member(person::email_) id

2) Use a third party library.  For example, LiteSQL

LiteSQL is a C++ library that integrates C++ objects tightly to relational database and thus provides an object persistence layer. LiteSQL supports SQLite3, PostgreSQL and MySQL as backends.


3) Manually store each object or class member in an external storage

See an example below:

Serializing Built-in Datatypes

Ultimately, every object consists of built-in data members such as int, bool, char [] and so on. Your first task is to write such datatypes to an ofstream (read more on <fstream> file I/O in the "Streams" sections). The application must store the values in their binary format. For this purpose, use the write() and read() member functions. write() takes the address and the size of a variable and writes its bit pattern to a file stream. read() takes two arguments of type char * and long which contain buffer's address and its size in bytes, respectively. The following example demonstrates how to store two integers in an ofstream:

#include <fstream>
using namespace std;
int main()
{
 int x,y; //mouse coordinates
 //..assign values to x and y
 ofstream archive("coord.dat", ios::binary);
 archive.write(reinterpret_cast<char *>(&x), sizeof (x));
 archive.write(reinterpret_cast<char *>(&x), sizeof (x));
 archive.close();
}


Farther Reading: 


Avalible on doqqa.com.   Doqqa is one my projects as well.
Comments: