3
我试图检查std::shared_ptr
是否为空。是否有这样做有没有推荐的方法来测试智能指针是否为空?
std::shared_ptr<int> p;
if (!p) { // method 1 }
if (p == nullptr) { // method 2 }
我试图检查std::shared_ptr
是否为空。是否有这样做有没有推荐的方法来测试智能指针是否为空?
std::shared_ptr<int> p;
if (!p) { // method 1 }
if (p == nullptr) { // method 2 }
之间的差异有没有这样做
std::shared_ptr<int> p; if (!p) { // method 1 } if (p == nullptr) { // method 2 }
没有,有没有差异之间的差异。这两种操作都有properly defined overload。
另一个相当于是
if(p.get() == nullptr)
理论上第三者在相对疯狂的情况下可能更复杂,因为它必须在比较nullptr之前得到'T *'。设想一种类型擦除的智能指针,在获得'T *'之前必须调用一个vtable方法,但是如果值为null,则保证nullptr vtable。方法1和2可以将可能的extract-'T *'短路,而3不能,因为'.get()'不知道它会被检查为空。 – Yakk
没有区别的。你也可以写if(not p.get()) –
if(p.get()== nullptr)''? –
没有区别。一个是少打字。 – Galik