RAII for Xerces

We have already seen how to install and run Apache Xerces-C 3 on Windows Seven / VC++ 2010.

Before starting using it, let's simplify a bit our life creating a little class that would spare us the bore of initialize and terminate explicitly Xerces.

The rationale behind it is that Xerces is a resource that has to be initialized before using it and released at the end, so it makes perfect sense applying the RAII (Resource Acquisition Is Initialization) paradigm.

Besides, it is very easy to design and implement. It just a matter of writing this tiny class:
#include <iostream>
#include <xercesc/util/PlatformUtils.hpp>
XERCES_CPP_NAMESPACE_USE

class XercesManager
{
public:
   XercesManager()
   {
      std::cout << "Initializing Xerces" << std::endl;
      XMLPlatformUtils::Initialize();
   }

   ~XercesManager()
   {
      std::cout << "Terminating Xerces" << std::endl;
      XMLPlatformUtils::Terminate();
   }
};
Given this wrapper class, our main becomes:
int main(int argc, char* argv[])
{
   try
   {
      XercesManager xm;
      someFunction(argc, argv); 
   }
   catch(const XMLException& ex)
   {
      std::cout << "Failure on Xerces: " << ex.getMessage() << std::endl;
   }

   system("pause");
   return 0;
}
Where in someFunction() there will be the actual code requiring Xerces.

We put on the stack a XercesManager instance. Its allocation determine the Xerces initialization; and when we leave the scope (both in case of exception and regular termination) the termination call is made through the destructor.

And now we can focus on the real job.

No comments:

Post a Comment