views:

174

answers:

2

I have the following code snippet:

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

Am I testing correctly? The boost docs say that a shared_ptr can be implicitly converted to a bool, but when I run this code it segfaults:

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;
+4  A: 

Yes, you are testing it correctly.

Your problem, however, is likely caused by dereferencing an invalid iterator. Check that returnsAnIterator() always returns an iterator that is not vector.end() and the vector is not modified in between, or empty.

jpalecek
The iterator is `vector.begin()`, so apparently I was testing the wrong thing. Thanks for your help.
Max
+1  A: 

Yes, the code you have above is correct. shared_ptr can be implicitly converted to a bool to check for null-ness.

The problem you have is your returnAnIterator() function is returning an invalid iterator. Probably it is returning end() for some container, which is one past the end of the container, and thus cannot be dereferenced as you're doing with *it.

SoapBox