我有以下代码片段:
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;
是的,您上面的代码是正确的。shared_ptr
可以隐式转换为 bool 以检查是否为空。
你遇到的问题是你的returnAnIterator()
函数返回无效的迭代器。或许它正在回归end()
对于某些容器,这是一个past容器的末尾,因此不能像您所做的那样取消引用*it
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)