0

I have classes like this:

class MyClass{
    int myField1;
    int myField2;

    MyMemento* getMemento(){
        auto m = new MyMemento();
        m->myField1 = myField1;
        m->myField2 = myField2;
    }

    void restore(MyMemento* m){
        myField1 = m->myField1;
        myField2 = m->myField2;
    }
}

class MyMemento{
public:
    int myField1;
    int myField2;
}

I have many classes like MyClass, each with their own unique member variables. But the pattern of the functions for creating / restoring the memento is the same, and the actual memento object simply contains variables matching each class.

This seems very tedious to implement for each class, so was wondering if there is some readymade class, library or pattern I can use to implement this instead ?

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190
  • 2
    You could extract the variables into a common `Storage` struct which both the memento and the original class use. Might be a valid case for private or protected inheritance if you want to keep the current syntax. – Quimby Mar 01 '22 at 08:54
  • That's a good idea. But I guess I would need to create a Storage struct for each class type. – Rahul Iyer Mar 01 '22 at 08:56
  • 1
    Yeah, but you have to write the fields somewhere anyway, there is no code generation in C++ sadly. – Quimby Mar 01 '22 at 08:57
  • @Quimby - Maybe this is a dumb question - but why wouldn't I just copy the instance of the class itself, and store it somewhere ? (assuming it has no pointers etc). Then making a copy is just one line.... – Rahul Iyer Mar 01 '22 at 09:08
  • 1
    Google Protobuf (other libraries exist) the keyword you are looking for is "serialisation". – Richard Critten Mar 01 '22 at 09:16
  • 1
    @RahulIyer You definitely can, that's even better than `Storage`, I assumed there was some reason why there is a separate `Memento` class. – Quimby Mar 01 '22 at 09:38
  • @Quimby Not entirely sure. I was just trying to implement memento based on a book I was reading. I guess the point of the object is maybe for compactness, or if some processing is required when restoring an object, or if there are some pointers in use somewhere. I'm still trying to understand the best way. – Rahul Iyer Mar 01 '22 at 09:50
  • @RahulIyer I don't have much experience with that pattern, but the memento object is there to restore a certain version of the original, how is it done can differ. It could e.g. be a filename that loads the contents from some backup file on disk. Hence the reason for two types. – Quimby Mar 01 '22 at 10:09
  • @Quimby makes sense. – Rahul Iyer Mar 01 '22 at 10:10

0 Answers0