我想检查一个 std::shared_ptr
是否为 null。做以下两种方式是否有区别?
std::shared_ptr<int> p;
if (!p) { // method 1 }
if (p == nullptr) { // method 2 }
我想检查一个 std::shared_ptr
是否为 null。做以下两种方式是否有区别?
std::shared_ptr<int> p;
if (!p) { // method 1 }
if (p == nullptr) { // method 2 }
Is there a difference between doing
std::shared_ptr<int> p; if (!p) { // method 1 } if (p == nullptr) { // method 2 }
没有区别。这两个操作都有适当定义的重载。
另一个等效的操作是
if(p.get() == nullptr)
T*
。想象一下一个类型擦除的智能指针,在获取T*
之前必须调用vtable方法,但如果该值为空,则保证vtable为nullptr。方法1和2可以短路可能的提取-T*
,而3不能,因为.get()
不知道它将仅被检查是否为空。 - Yakk - Adam Nevraumontshared_ptr
提供了一个特定的 bool 转换运算符 std::shared_ptr::operator bool
。
测试是否未设置:
if (!p)
测试是否设置:
if (p)
你可以通过以下方式非常明确地表达你的意图:
if (static_cast<bool>(p))
nullptr
,所以对于这个问题来说,p != nullptr
更加明确。在你的示例中,你只是明确了你想调用 operator bool
的意图。 - Sergey Kolesnik
if (p.get() == nullptr)
怎么样? - πάντα ῥεῖ