Learning Hub Search Ctrl K

MFC › 3. Document/View Architecture

Serialization and CArchive

Saving and loading documents with Serialize().

intermediate #mfc#serialization#carchive#cobject#declare_serial#schema#versioning#persistence

Explanation

Serialization is MFC’s way to save and load objects. A CArchive object attached to a CFile provides the same << (store) and >> (load) operators for both directions, and ar.IsStoring() / ar.IsLoading() tell them apart.

For your own class:

  1. Derive from CObject and add DECLARE_SERIAL(Class) in the header.
  2. Add IMPLEMENT_SERIAL(Class, BaseClass, schema) in one .cpp. The schema number is a version.
  3. Provide a default constructor.
  4. Override Serialize(CArchive&): write or read each member, calling the base class’s Serialize first.

Capabilities:

  • Basic types and CString, CPoint, CRect, CTime work with << / >>; CArray, CList, CMap, CObList, CObArray have their own Serialize.
  • Pointers to CObject-derived objects are stored with their class name, so ar << pShape; ... ar >> pShape; restores the right derived class polymorphically.
  • Multiple references to the same object are stored once.
  • Versioning: IMPLEMENT_SERIAL(Class, Base, VERSIONABLE_SCHEMA | 2) lets ar.GetObjectSchema() return the stored version while loading, so you can read older files.
  • In a document-based app, CDocument::Serialize is called by File Open/Save for you.

Example

A console program that saves a list of shapes to a file and reads it back:

#include <afxwin.h>
#include <iostream>

class CBox : public CObject {
    DECLARE_SERIAL(CBox)
public:
    CBox() : m_w(0), m_h(0) {}                             // required by serialization
    CBox(const CString& n, int w, int h) : m_name(n), m_w(w), m_h(h) {}
    void Serialize(CArchive& ar) override {
        CObject::Serialize(ar);
        if (ar.IsStoring()) {
            ar << m_name << m_w << m_h;                    // write in this order...
        } else {
            ar >> m_name >> m_w >> m_h;                    // ...and read in the SAME order
        }
    }
    CString m_name;
    int m_w, m_h;
};
IMPLEMENT_SERIAL(CBox, CObject, 1)

int _tmain() {
    if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;

    TCHAR tmp[MAX_PATH];
    GetTempPath(MAX_PATH, tmp);
    CString path = CString(tmp) + _T("boxes.dat");

    try {
        {   // ---- store
            CObList list;
            list.AddTail(new CBox(_T("small"), 2, 3));
            list.AddTail(new CBox(_T("large"), 20, 30));

            CFile file(path, CFile::modeCreate | CFile::modeWrite);
            CArchive ar(&file, CArchive::store);
            list.Serialize(ar);                            // count + each object with its class info
            ar.Close();
            file.Close();
            while (!list.IsEmpty()) delete list.RemoveHead();
        }
        {   // ---- load
            CObList list;
            CFile file(path, CFile::modeRead);
            CArchive ar(&file, CArchive::load);
            list.Serialize(ar);                            // objects are re-created by class name
            for (POSITION pos = list.GetHeadPosition(); pos; ) {
                CBox* pBox = DYNAMIC_DOWNCAST(CBox, list.GetNext(pos));
                if (pBox)
                    std::wcout << (LPCTSTR)pBox->m_name << L": " << pBox->m_w << L"x" << pBox->m_h << L"\n";
            }
            while (!list.IsEmpty()) delete list.RemoveHead();
        }
        CFile::Remove(path);
    } catch (CException* e) {                              // MFC throws pointers: you must Delete()
        TCHAR msg[256];
        e->GetErrorMessage(msg, 256);
        std::wcout << L"error: " << msg << L"\n";
        e->Delete();
        return 1;
    }
    return 0;
}

Common pitfalls

  • Read in the same order you write, with the same types. A mismatch silently corrupts the data or throws on the next read.
  • Change the layout without bumping the schema and old files will load wrongly. Use VERSIONABLE_SCHEMA and branch on ar.GetObjectSchema().
  • The class needs a default constructor; CreateObject has no arguments.
  • MFC exceptions are thrown by pointer: catch CException* and call Delete() (or use CException* e with e->Delete()), unlike standard exceptions.
  • Loaded objects are heap-allocated by the archive: you own them and must delete them (the document’s DeleteContents is the usual place).
  • Serialization writes a binary, MFC-specific format (not portable to other tools). For interchange prefer XML/JSON and a proper library.
  • int and long sizes vary by platform; for a stable format use fixed-width types (DWORD, LONGLONG).

Legacy vs modern

Serialization is a 1990s technique. Today you’d store settings and data as JSON or XML (nlohmann/json, pugixml, MSXML) or in SQLite, which survive version changes and work with other languages. Keep MFC serialization for existing document formats (see Document, Views and Frames).

Exercises

1. Why does CBox need a default constructor?

When loading, MFC creates the object from the stored class name with CreateObject() (no arguments) and then calls Serialize to fill it.