Search code examples
c++shared-ptrxerces

Xerces-c & shared_ptrs


I'm new to the concept of shared_ptr and was trying to reconstruct my program such that it is using smart pointers instead of the regular ones. I ama trying to use shared_ptr with Xerces-c and I am having trouble initializing my errorhandler.

I have a class that implements the errorHandler.

class Handler: public ErrorHandler {
public:
    void warning (const SAXParseException&) {   cerr << "THIS IS A WARNING\n";}
    void error (const SAXParseException&) { cerr << "THIS IS A ERROR\n"; return;}
    void fatalError(const SAXParseException&) { cerr << "THIS IS A FATALERROR\n";}
    void resetErrors() {}
}

In the implementation I am trying to pass the class that I've implemented from ErrorHandler into the setErrorHandler function:

   boost::shared_ptr<XercesDOMParser> m_Parser;
   boost::shared_ptr<Validator> m_ErrorHandler;
   m_ErrorHandler = boost::shared_ptr<Handler>(new Handler());
   m_Parser->setErrorHandler(m_ErrorHandler);

But it errors out on the last line because the type doesnt match up:

Error: no matching function for call to ‘xercesc_3_1::XercesDOMParser::setErrorHandler(boost::shared_ptr&)’ /opt/include/xercesc/parsers/XercesDOMParser.hpp:236: note: candidates are: void xercesc_3_1::XercesDOMParser::setErrorHandler(xercesc_3_1::ErrorHandler*)

With regular pointers, it was fine to say:

     XercesDOMParser * m_Parser;
     Handler * errorHandler;
m_Parser = new XercesDOMParser;
errorHandler = new Handler();
m_Parser->setErrorHandler(errorHandler);

But when using smart pointers, how is this initialization done? Thanks


Solution

  • If the m_Parser doesn't take a shared_ptr, you can't make it. shared_ptr's aren't a silver bullet, you can only use them in your own code. You can use the .get() method to return the raw pointer under the smart pointer for compatibility with legacy code.