测试shared_ptr是否为NULL

Max*_*Max 11 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
Run Code Online (Sandbox Code Playgroud)

我测试正确吗?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;
Run Code Online (Sandbox Code Playgroud)

Soa*_*Box 8

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

你遇到的问题是你的returnAnIterator()函数返回一个无效的迭代器.可能它正在返回end()一些容器,这是一个超过容器末端的容器,因此不能像你一样去解除引用*it.


jpa*_*cek 7

是的,您正在测试它.

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