PDA

View Full Version : Check if a object is null and destroy objects



ruben.rodrigues
30th June 2010, 12:07
Hi people!

I want to know how I can check if a variable that allocates a class is empty or not and I also want to know how to destroy it.

this is because I have a variable that is an array of a class:

ClassUser *user[5];

then at some point in the code:

user[connection_number] = new ClassUser();

this is needed because I must handle multiple connection to a server and they can't be more than the number of sql licenses that we have.

thanks in advance!

high_flyer
30th June 2010, 14:25
You have to initialized the pointers to NULL first.
You will be wise to use a container class istead of a naked pointer too.
something like :


QVector<ClassUser*> vecUsers;

//When intilaizing you do (probably in a for loop):
vecUsers.push_back(new ClassUser());

//when cleaning up:
for(int i=0; i<vecUsers.size(); i++) {//some like to use 'foreach'
if(vecUsers.at(i))
delete vecUsers[i];
}
vecUsers.clear();


note in the code above there is no need to initialize to NULL, since the vector is empty when there are not items in it,and any item in it is either NULL if new failed, or a valid pointer.
This approach is good if you just need to hold the pointer array and use it.

If this has to be a dynamic array that gets and removes items, a different approach might be needed, but that depends on your application internals.

lyuts
2nd July 2010, 09:33
There is a handy qDeleteAll() for cleaning such containters. So you don't need to write that loop where you delete vecUsers[i].

high_flyer
2nd July 2010, 10:25
Correct, just make sure the type is a pointer when using, and in the case above it would fit good.