if (x->isNull()) crashes if x is not initialized
Hi,
I wanted to use (x->isNull()) to find out, if I can safely use a pointer to something. However, if I use it like this:
Code:
SomeType *x;
//doing some work, perhaps giving x a new object to point to, perhaps not
if (x->isNull()) return false;
the program crashes on the if-condition. I can see why: there is no object to get the ->isNull() method from.
If I use:
Code:
if (x==0) return false;
instead, it works.
Now I have three curious questions:
- Is it "legal" (aka: advisable) to use the second approach?
- Will *-Declarations ensure that the Variable points to 0 before it gets an object to point to?
- Is there any use for ->isNull()?
Re: if (x->isNull()) crashes if x is not initialized
Of course (x == 0) works, because an object has not been created using new operator.
1. Yes, it's legal, but you have to initialize local variables, eg SomeType *x = 0; or create a new object using new operator.
2. That's right. You have to check if a pointer is not 0.
3. If object has been allocated.
NOTE: all these question are C++ question, but not about Qt.
PS. see nice C++ reference.
Re: if (x->isNull()) crashes if x is not initialized
To stay on Qt, note that Qt has smart pointers ! (QSharedPointer, ...)
Re: if (x->isNull()) crashes if x is not initialized
Thank you, spirit, I will make sure to initialize everything with =0 from now on!
to 3.:
If object is allocated, ->isnull() must be false, right? Because there can be nothing that's allocated in Null....
You've stated correctly, that this is more about a c++ understanding thing, but as the ->isNull() method is belonging to Qt data types I thought it might be correct to ask here, sorry if I'm mistaken!
Re: if (x->isNull()) crashes if x is not initialized
isNull for most of the Qt's classes means that an object has no data.