Results 1 to 4 of 4

Thread: Check if a object is null and destroy objects

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    Join Date
    Jan 2006
    Location
    Munich, Germany
    Posts
    4,714
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows
    Thanks
    21
    Thanked 418 Times in 411 Posts

    Default Re: Check if a object is null and destroy objects

    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 :
    Qt Code:
    1. QVector<ClassUser*> vecUsers;
    2.  
    3. //When intilaizing you do (probably in a for loop):
    4. vecUsers.push_back(new ClassUser());
    5.  
    6. //when cleaning up:
    7. for(int i=0; i<vecUsers.size(); i++) {//some like to use 'foreach'
    8. if(vecUsers.at(i))
    9. delete vecUsers[i];
    10. }
    11. vecUsers.clear();
    To copy to clipboard, switch view to plain text mode 

    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.
    Last edited by high_flyer; 30th June 2010 at 15:30.
    ==========================signature=============== ==================
    S.O.L.I.D principles (use them!):
    https://en.wikipedia.org/wiki/SOLID_...iented_design)

    Do you write clean code? - if you are TDD'ing then maybe, if not, your not writing clean code.

Similar Threads

  1. how to check for NULL reference?
    By metow in forum Newbie
    Replies: 2
    Last Post: 14th December 2009, 03:23
  2. How to destroy an object right
    By Cruz in forum Newbie
    Replies: 7
    Last Post: 22nd January 2009, 20:43
  3. Object Not destroy
    By Sudhanshu Sharma in forum Qt Programming
    Replies: 3
    Last Post: 31st July 2008, 00:16
  4. Replies: 7
    Last Post: 18th July 2006, 22:33
  5. Replies: 1
    Last Post: 24th June 2006, 21:55

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.