Search code examples
c++pointerssmart-pointersxerces

Convert a raw pointer to a clone_ptr


I have a clone_ptr implementation, as was shown in this question and I have a problem where I need to create a clone_ptr from a raw pointer returned from a function.

Here is the code:

DOMDocument* doc =  impl->createDocument(
                                                0,                   // root element namespace URI.
                                                XML::X(docname.c_str()),  // root element name
                                                0);                  // document type object (DTD).
        document.get() = *doc;  //No way to assign clone_ptr document to raw doc pointer

Where document& impl are declared as follows:

clone_ptr<DOMImplementation, default_clone<DOMImplementation> > impl; 
    clone_ptr<DOMDocument, default_clone<DOMDocument> > document;

The createDocument function above returns a raw DOMDocument pointer and is assigned to the local variable doc, now I want to get my document clone_ptr and actually pass it the raw pointer gotten from the create document function. It seems however the compiler is not too happy with this as it says the following:

 error C2440: '=' : cannot convert from 'xercesc_3_1::DOMDocument' to 'clone_ptr<T,Cloner>::pointer'
        with
        [
            T=xercesc_3_1::DOMDocument,
            Cloner=default_clone<xercesc_3_1::DOMDocument>
        ]

So my question is how can I allow a raw pointer to be explicitly or implicitly converted to a clone_ptr? EDIT:

Clone specialization:

template<typename T>
struct default_clone
{
    static T* clone(T* pPtr)
    {
        return pPtr ? pPtr->clone() : 0;
    }
};

template<>
struct default_clone<DOMDocument>
{
    static DOMDocument* clone(DOMDocument* pPtr)
    {
        DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(XML::X("Core"));
        return pPtr ? impl->createDocument(0, XML::X(""), 0) : 0;
    }
};

template<>
struct default_clone<DOMImplementation>
{
    static DOMImplementation* clone(DOMImplementation* pPtr)
    {
        return pPtr ? DOMImplementationRegistry::getDOMImplementation(XML::X("Core")) : 0;
    }
};

Solution

  • Giving your clone_ptr implementation, and the fact that doc is a pointer, wouldn't it be document.reset(doc)?