QSharedPointer::isNull() 和运算符之间的区别!().

Difference between QSharedPointer::isNull() and operator!()

本文关键字:区别 之间 isNull QSharedPointer 运算符      更新时间:2023-10-16

在Qt文档中,我们读到:

bool QSharedPointer::operator! () const
Returns true if this object is null. 
This function is suitable for use in if-constructs, like:
 if (!sharedptr) { ... }

bool QSharedPointer::isNull () const
Returns true if this object is holding a reference to a null pointer.

这两个功能有什么区别?这很清楚什么是对空指针的引用,但这里意味着什么

"如果对象为空" ?

什么决定了QSharedPointer是否为空?这些功能如何对应于QSharedPointer::data() != null

来自QSharedPointer类的Qt来源:

inline bool operator !() const { return isNull(); }

这证实了@JoachimPileborg在他的评论中所说的话——isNull()功能和operator!()是等价的。

"null" QSharedPointer 包装一个 T* t,其中 t 等于 0/NULL/nullptr。这就是"对象为空"的含义

isNull() 和运算符!() 是等效的,您可以使用其中任何一个。

默认情况下,共享指针为 null,或者显式设置为 0/nullptr 时:

QSharedPointer<T> t; //null
QSharedPointer<T> t2(new T); //not null
QSharedPointer<T> t3(0); //null
QSharedPointer<T> t4(nullptr); //null
t2.clear(); //not null before, now null