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

醉酒当歌 提交于 2020-02-03 16:27:42

问题


in Qt docs we read:

bool QSharedPointer::operator! () const

Returns true if this object is null. 
This function is suitable for use in if-constructs, like:

 if (!sharedptr) { ... }

and

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

What is the difference between these two functions? This is clear what is reference to a null pointer, but what means here

"if the object is null" ?

What determines if QSharedPointer is null? How do these functions correspond to QSharedPointer::data() != null ?


回答1:


From Qt sources of the QSharedPointer class:

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

This confirms what @JoachimPileborg said in his comment - isNull() function and operator!() are equivalent.




回答2:


A "null" QSharedPointer wraps a T* t where t equals 0/NULL/nullptr. That's what's meant with "object is null"

isNull() and operator!() are equivalent, you can use either one.

A shared pointer is null by default, or when set to 0/nullptr explicitly:

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


来源:https://stackoverflow.com/questions/19925693/difference-between-qsharedpointerisnull-and-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!