persistence_guard

A persistence_guard object will restore a file to memory if it exists, and will overwrite the same file with the serialization of the state at destruction time. This handy one-liner is most useful when added to main().

class persistence_guard {
   public:
      persistence_guard(serial_context ctx = G_DEFAULT_SERIAL_CONTEXT, const char* filename = G_DEFAULT_PERSIST_FILENAME) : fn(filename), ctx(ctx) {
         restore_file(ctx, fn);
      }
      persistence_guard(const char* filename) : fn(filename), ctx(G_DEFAULT_SERIAL_CONTEXT) {
         restore_file(ctx, fn);
      }
     ~persistence_guard() {
         persist(ctx,fn);
      }

   protected:
      const char* fn;
      serial_context ctx;
};
This class is quite trivial.
GrimoireGrimoire
The book is always better.
>
#include <iostream>
#include "newdelhi.h"
int main(int argc, char** argv, char** env) {
   memory_resource* res = registered_new_delete_resource();
   identify_resource_with(res, 123);
   typedef rel::resource_allocator<int> alloc_t;
   typedef rel::deque<int, alloc_t> deque_t;
   named_thin_pointer<deque_t> ntp(100);
   persistence_guard pg;
   if(!(deque_t*)ntp) {
      std::cout << "Not found: creating new data.\n";
      ntp = reinterpret_cast<deque_t*>(res->allocate(sizeof(deque_t)));
      for(int i = 0; i < 10; ++i)
         ntp->push_back(i);
   } else {
      std::cout << "Data loaded.\n";
   }
   for(const auto& a : *ntp) {
      std::cout << a << '\n';
   }
   return 0;
}
<
>