Search code examples
c++serializationboostfactory-pattern

boost::serialization and factory pattern design


I have protected my constructors in a component-based game engine skeleton I'm working on, so that Components are created in a GameSystem that handles ownership assignment and attaches them to GameObjects. The protected constructor of a Component takes a GameObject&, since its owner will always exist throughout the Component's lifetime.

I tried to apply serialization to Component classes by overriding the load_construct_data() and save_construct_data() functions and making them friends of Component, but I would end up with something like this:

template<class Archive>
inline void load_construct_data(Archive& ar, Component* t, const unsigned int file_version)
{
        // Retrieve data from archive required to construct new instance
        GameObject gameObject; // This is illegal since GameObject() is protected.
        ar >> gameObject;
        // Invoke inplace constructor to initialize instance of my_class
        ::new(t)Component(gameObject);
}

I can create a GameObject through GameSystem as well, or make load_construct_data a friend of GameObject. I don't like the proliferation of friendships, but does the first option make sense? Would the serialization library somehow keep track of the object, even though it wasn't created through its constructor? Remember I need to load each object only once.

Or does it call for a major redesign?


Solution

  • I have made GameObjects have a public constructor to allow access. Solves the issue, if in a somewhat clunky manner.