Results 1 to 12 of 12

Thread: Qt and global variables

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    Join Date
    May 2006
    Location
    Germany
    Posts
    108
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows
    Thanks
    2
    Thanked 14 Times in 12 Posts

    Default Re: Qt and global variables

    Quote Originally Posted by Morea View Post
    The singleton code looks nice. I'll try to use that. Thanks!
    The Singleton implementation described is used widely but also contains a race-condition when it comes to use in a multithreaded program (see Alexandrescu's "Modern C++ Design" for further details).

    Qt Code:
    1. class MyClass
    2. {
    3. MyClass() {};
    4. virtual ~MyClass() {};
    5.  
    6. public:
    7. static MyClass* instance()
    8. {
    9. static QMutex mutex;
    10. if ( !m_pInstance )
    11. {
    12. mutex.lock();
    13. if (!m_pInstance)
    14. m_pInstance = new MyClass;
    15. mutex.unlock();
    16. }
    17.  
    18. return m_pInstance;
    19. }
    20.  
    21. void doSomething()
    22. {
    23. // ...
    24. }
    25.  
    26. protected:
    27. static MyClass* m_pInstance;
    28. };
    29.  
    30. MyClass* MyClass::m_pInstance = NULL;
    To copy to clipboard, switch view to plain text mode 
    Last edited by Methedrine; 24th January 2007 at 15:45. Reason: added code for thread-safe singleton

  2. The following user says thank you to Methedrine for this useful post:

    sunil.thaha (2nd February 2007)

Similar Threads

  1. Replies: 1
    Last Post: 22nd January 2007, 09:41
  2. Declarate global parameters
    By Dark_Tower in forum Qt Programming
    Replies: 7
    Last Post: 11th December 2006, 18:01
  3. Global variables
    By Mariane in forum Newbie
    Replies: 14
    Last Post: 10th October 2006, 17:23
  4. Creating a global array in my code???
    By therealjag in forum General Programming
    Replies: 5
    Last Post: 13th March 2006, 11:13
  5. declaration of global variables???
    By pranav_kavi in forum Newbie
    Replies: 6
    Last Post: 31st January 2006, 19:56

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.