Library function returns raw pointer and I want to use smart pointer

c++, smart-pointers

Solution

I guess the library provides a way of releasing those raw pointers ?

If so, you can just "create" a `shared_ptr` with a custom deleter, specifying the "free function" provided by the library.

Example:

If you have the two functions:

Foo* createFoo();
void freeFoo(Foo* foo);

You can create a `shared_ptr` that way:

boost::shared_ptr<Foo> foo(createFoo(), freeFoo);

If the raw pointer is not meant to be released, you can instead provide a "null-deleter" that does nothing when the reference counter reaches 0.

Problem

I have this situation where the library I use has many functions that return raw pointers to objects, how could I now use boost smart pointers in my program using this library and using smart pointers? The library is xerces-C++ and an example is getting the document iterator: ``` boost::shared_ptr<DOMNodeIterator> itera = document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true); ``` The `createNodeIterator` function returns a pointer to a `DOMNodeIterator` object, this is a raw pointer and therefore cannot be cast just like that to a `boost::shared_ptr`... How would I best deal with this? Use raw pointers instead?

Original source