C++ 测试 shared_ptr 是否为 NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3431855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:49:54  来源:igfitidea点击:

testing if a shared_ptr is NULL

c++nullshared-ptr

提问by Max

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:

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

采纳答案by jpalecek

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.

但是,您的问题很可能是由取消引用无效迭代器引起的。检查是否returnsAnIterator()总是返回一个不存在的迭代器,vector.end()并且向量在两者之间没有被修改,或者是空的。

回答by SoapBox

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

是的,你上面的代码是正确的。 shared_ptr可以隐式转换为 bool 以检查空性。

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

您遇到的问题是您的returnAnIterator()函数返回了一个无效的迭代器。也许它返回end()一些容器,这是一个过去的容器的结束,因为你与做因而不能被解除引用*it