测试shared_ptr是否为NULL

时间:2010-08-07 20:02:40

标签: 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

我测试正确吗? 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;

2 个答案:

答案 0 :(得分:8)

是的,您上面的代码是正确的。 shared_ptr可以隐式转换为bool以检查null-ness。

您遇到的问题是returnAnIterator()函数返回了无效的迭代器。可能它正在为某个容器返回end(),这是一个过去容器的末尾,因此无法在您使用*it时解除引用。

答案 1 :(得分:7)

是的,您正在测试它。

然而,您的问题可能是由解除引用无效的迭代器引起的。检查returnsAnIterator()是否总是返回不是vector.end()的迭代器,并且中间没有修改向量,或者为空。