PDA

View Full Version : if (x->isNull()) crashes if x is not initialized



sedi
8th August 2012, 12:04
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:


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:


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()?

spirit
8th August 2012, 12:15
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 (http://www.parashift.com/c++-faq-lite/index.html).

thomas@itest
8th August 2012, 12:34
To stay on Qt, note that Qt has smart pointers ! (QSharedPointer, ...)

sedi
8th August 2012, 14:54
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!

spirit
8th August 2012, 15:15
isNull for most of the Qt's classes means that an object has no data.