库函数返回原始指针,我想使用智能指针
我遇到这种情况,我使用的库有许多函数返回到对象的原始指针,我现在如何在使用该库和智能指针的程序中使用 boost 智能指针?
该库是 xerces-C++,一个示例是获取文档迭代器:
boost::shared_ptr<DOMNodeIterator> itera = document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true);
createNodeIterator
函数返回一个指向 DOMNodeIterator
对象的指针,这是一个原始指针,因此无法进行强制转换就像 boost::shared_ptr
一样...我该如何最好地处理这个问题?使用原始指针代替?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜这个库提供了一种释放这些原始指针的方法?
如果是这样,您可以使用自定义删除器“创建”一个
shared_ptr
,指定库提供的“自由函数”。示例:
如果您有两个函数:
您可以这样创建一个
shared_ptr
:如果 raw 指针不打算被释放,您可以提供一个“null-当引用计数器达到 0 时,它不执行任何操作。
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:
You can create a
shared_ptr
that way: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.
您可以更改
boost::shared_ptr; itera = document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true);
到boost::shared_ptr; itera( document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true));
它应该可以正常编译。You can change
boost::shared_ptr<DOMNodeIterator> itera = document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true);
toboost::shared_ptr<DOMNodeIterator> itera( document->createNodeIterator(rootelement, DOMNodeFilter::SHOW_ALL, NULL, true));
and it should compile fine.如果您在本地创建对象,请使用 boost::scoped_ptr 而不是 boost:shared_ptr ,因为如果您将其作为参数传递给其他函数,这是非常危险的。如果您正在处理shared_ptr,您也必须考虑对象引用计数。
如果使用 Scoped_ptr,当对象的作用域结束时它会自动删除。
Foo 类
boost::scoped_ptr objfoo(new Foo());
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());