The library function returns a raw pointer, and I want to use a smart pointer

I have a situation where in the library that I use, there are many functions that return the original pointers to objects, how can I now use raising smart pointers in my program, using this library and using smart pointers?

The library is xerces-C ++, and the example is a document iterator:

boost::shared_ptr<DOMNodeIterator> itera = document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true);

The function createNodeIteratorreturns a pointer to an object DOMNodeIterator, it is a raw pointer and therefore cannot be assigned exactly the same to boost::shared_ptr... How should I deal with this? Use raw pointers instead?

+3
source share
3

, raw?

, "" shared_ptr , " ", .

:

:

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

shared_ptr :

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

raw , " ", , 0.

+6

boost::shared_ptr<DOMNodeIterator> itera = document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true); boost::shared_ptr<DOMNodeIterator> itera( document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true));, .

0

If you create the object locally, use boost :: scoped_ptr instead of boost: shared_ptr, as it is very dangerous if you pass any other function as a parameter. If you are dealing with shared_ptr, you are also thinking of counting object references.

If you use Scoped_ptr, it is automatically deleted when the scope of the object ends.

Class Foo boost :: scoped_ptr objfoo (new Foo ());

0
source

Source: https://habr.com/ru/post/1771646/


All Articles