What it is
Cereal is a C++11 library for serialization of data structures. It allows converting C++ objects to JSON, XML, or binary formats, and deserializing them back into objects efficiently and safely.
Cereal allows serialization of standard C++ data types, STL containers, and custom classes. You can serialize objects to JSON, XML, or binary archives, and deserialize them with minimal boilerplate.
Installation
sudo apt install libcereal-devGetting started
The smallest useful thing you can do with it, and what each part means.
#include <cereal/archives/json.hpp>
#include <fstream>
struct MyData {
int x; float y;
template<class Archive>
void serialize(Archive & ar) {
ar(x, y);
}
};
int main() {
MyData data{42, 3.14f};
std::ofstream os("data.json");
cereal::JSONOutputArchive archive(os);
archive(data);
}#include <cereal/archives/json.hpp>
#include <fstream>
MyData data;
std::ifstream is("data.json");
cereal::JSONInputArchive archive(is);
archive(data);
std::cout << data.x << ", " << data.y << std::endl;Advanced usage
Where the library earns its place over a simpler alternative.
#include <cereal/archives/json.hpp>
#include <vector>
#include <fstream>
int main() {
std::vector<int> numbers{1,2,3,4,5};
std::ofstream os("numbers.json");
cereal::JSONOutputArchive archive(os);
archive(numbers);
}struct Point { int x, y; template<class Archive> void serialize(Archive & ar){ ar(x,y); } };
struct Shape { Point p; int size; template<class Archive> void serialize(Archive & ar){ ar(p, size); } };#include <cereal/archives/binary.hpp>
std::ofstream os("data.bin", std::ios::binary);
cereal::BinaryOutputArchive archive(os);
archive(data);#include <cereal/archives/xml.hpp>
std::ofstream os("data.xml");
cereal::XMLOutputArchive archive(os);
archive(data);Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- ArchiveException
- Occurs if the archive cannot read/write data correctly. Check file paths and ensure the archive matches the serialized format.
- Type mismatch
- Ensure the types during deserialization match exactly what was serialized.
Best practices
- Use template `serialize` functions in your classes for custom serialization.
- Prefer binary archives for performance and JSON/XML for readability.
- Keep serialization code simple and minimal for maintainability.
- Avoid serializing pointers directly unless using smart pointers handled by Cereal.
- Ensure backward compatibility by adding default values when extending data structures.
Background
Why it exists, and what it was reacting to.
Cereal was developed by USCiLab to provide a modern, easy-to-use, and type-safe serialization library for C++. It leverages C++11 features like templates and smart pointers, making serialization and deserialization intuitive and flexible for both small and complex data structures.
