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 w开发者_开发技巧ith this?  Use raw pointers instead?
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.
You can change boost::shared_ptr<DOMNodeIterator> itera = document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true); to boost::shared_ptr<DOMNodeIterator> itera( document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true)); and it should compile fine.
If you are creating the object locally use boost::scoped_ptr instead of boost:shared_ptr as this is very dangerous if you pass as a parameter to some other function. If you are dealing with shared_ptr, you have think about object reference count as well.
If you use Scoped_ptr, it automatically deletes when scope of the object ends.
Class Foo boost::scoped_ptr objfoo(new Foo());
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论