3

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 ?

demonplus
  • 5,613
  • 12
  • 49
  • 68
4pie0
  • 29,204
  • 9
  • 82
  • 118

2 Answers2

6

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.

vahancho
  • 20,808
  • 3
  • 47
  • 55
3

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
Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70
  • @jdi: It has several reset() overloads in Qt 5: http://doc.qt.io/qt-5/qsharedpointer.html#reset But as clear() exists in both Qt 4 and Qt 5, this is indeed more generic. – Frank Osterfeld Jun 08 '15 at 15:08
  • Sorry. I was looking at Qt4 compatibility. I should have checked Qt5 before editing! – jdi Jun 08 '15 at 20:04