Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 915
Tony The Lion Avatar asked Dec 05 '25 12:12

Tony The Lion


1 Answers

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.

like image 57
ereOn Avatar answered Dec 11 '25 08:12

ereOn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!