测试shared_ptr是否为NULL
我有以下代码片段:
std::vector< boost::shared_ptr<Foo> >::iterator it;
it = returnsAnIterator();
// often, it will point to a shared_ptr that is NULL, and I want to test for that
if(*it)
{
// do stuff
}
else // do other stuff
我的测试正确吗? boost 文档说,shared_ptr 可以隐式转换为 bool,但是当我运行此代码时,它会出现段错误:
Program received signal SIGSEGV, Segmentation fault.
0x0806c252 in boost::shared_ptr<Foo>::operator Foo*
boost::shared_ptr<Foo>::* (this=0x0)
at /usr/local/bin/boost_1_43_0/boost/smart_ptr/detail/operator_bool.hpp:47
47 return px == 0? 0: &this_type::px;
I have the following code snippet:
std::vector< boost::shared_ptr<Foo> >::iterator it;
it = returnsAnIterator();
// often, it will point to a shared_ptr that is NULL, and I want to test for that
if(*it)
{
// do stuff
}
else // do other stuff
Am I testing correctly? The boost docs say that a shared_ptr can be implicitly converted to a bool, but when I run this code it segfaults:
Program received signal SIGSEGV, Segmentation fault.
0x0806c252 in boost::shared_ptr<Foo>::operator Foo*
boost::shared_ptr<Foo>::* (this=0x0)
at /usr/local/bin/boost_1_43_0/boost/smart_ptr/detail/operator_bool.hpp:47
47 return px == 0? 0: &this_type::px;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您上面的代码是正确的。
shared_ptr
可以隐式转换为 bool 以检查是否为空。您遇到的问题是您的
returnAnIterator()
函数返回无效的迭代器。可能它正在为某些容器返回end()
,这是容器末尾的一个过去,因此不能像使用* 那样取消引用它。
Yes, the code you have above is correct.
shared_ptr
can be implicitly converted to a bool to check for null-ness.The problem you have is your
returnAnIterator()
function is returning an invalid iterator. Probably it is returningend()
for some container, which is one past the end of the container, and thus cannot be dereferenced as you're doing with*it
.是的,您测试正确。
但是,您的问题可能是由于取消引用无效迭代器而引起的。检查
returnsAnIterator()
是否始终返回一个不是vector.end()
的迭代器,并且向量在其间未被修改或为空。Yes, you are testing it correctly.
Your problem, however, is likely caused by dereferencing an invalid iterator. Check that
returnsAnIterator()
always returns an iterator that is notvector.end()
and the vector is not modified in between, or empty.