kiriloff
kiriloff

Reputation: 26333

C++ QList in if statement, what is default value?

I find some code sample with these oddl lines

QList<TDataXml *> *newXMLData = input->getValue<QList<TDataXml *>>();
    if(newXMLData) 
    {
        // do things
    }

I dont understand if(newXMLData). This is a QList. When should statement be true or false? Why not use Qt isEmpty() method instead?

Thanks

Upvotes: 0

Views: 2146

Answers (4)

jrok
jrok

Reputation: 55425

newXMLData is pointer to QList and as such could be initialized to NULL. By testing the pointer in boolean context, you avoid dereferencing a NULL pointer, which would be undefined behaviour.

So in other words, the if statement isn't there to check whether the list is empty or not, it's there to check if the call to getValue() method returned a valid pointer. The statement will evaluate to true only if the pointer isn't NULL. Only then you can reliably call isEmpty() or any other method of the class the pointer points to.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361682

if(newXMLData) checks for nullity, because newXMLData is a pointer, and therefore it could point to no object, in which case it's value is nullptr (or NULL in C++03).

If newXMLData is not nullptr, then it will be true and the if-block will execute, otherwise false and if-block will not execute.

It is same as (C++11):

if(newXMLData != nullptr) //or if(newXMLData != NULL) in pre C++11
{
  //your code
}

Upvotes: 2

Lwin Htoo Ko
Lwin Htoo Ko

Reputation: 2406

Checking newXMLData is NULL or 0. But, newXMLData needs to be initialized 0 or NULL before if statement.

Upvotes: 0

Premkumar U
Premkumar U

Reputation: 115

if(newXMLData) means the pointer newXMLData points to a valid object or not. you cannot invoke methods of an object if the pointer points to nothing(NULL). So you need to test the pointer is valid or not.

Upvotes: 0

Related Questions