C++ 测试共享_ptr是否为空

C++ 测试共享_ptr是否为空,c++,null,shared-ptr,C++,Null,Shared Ptr,我有以下代码片段: 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 std::vector::迭代器

我有以下代码片段:

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
std::vector::迭代器;
it=returnsAnIterator();
//通常,它会指向一个空的共享\u ptr,我想对此进行测试
如果(*it)
{
//做事
}
否则我会做其他事情
我的测试正确吗?boost文档说共享的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;
程序接收信号SIGSEGV,分段故障。
boost::shared_ptr::运算符Foo中的0x0806c252*
boost::shared_ptr::*(this=0x0)
at/usr/local/bin/boost_1_43_0/boost/smart_ptr/detail/operator_bool.hpp:47
47返回px==0?0:&此类型::px;

是的,您正在正确测试它


然而,您的问题很可能是由取消引用无效迭代器引起的。检查
returnsAnIterator()
是否始终返回一个不是
vector.end()
的迭代器,并且该向量没有在其间修改或为空。

是的,上面的代码是正确的
shared_ptr
可以隐式转换为bool以检查空值


问题是
returnAnIterator()
函数返回的迭代器无效。可能它返回了某个容器的
end()
,该容器超过了容器的末尾,因此不能像使用
*它时那样取消引用,迭代器是
vector.begin()
,所以显然我测试的是错误的东西。谢谢你的帮助。