我有以下代码片段:

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

我测试正确吗?增强文档说可以将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;

最佳答案

是的,您正在正确测试它。

但是,您的问题很可能是由取消引用无效的迭代器引起的。检查returnsAnIterator()始终返回不是vector.end()的迭代器,并且 vector 在两者之间未修改或为空。

07-24 09:37
查看更多