Results 1 to 2 of 2

Thread: Thread safe initialization of const variable in header file

  1. #1
    Join Date
    Aug 2013
    Posts
    17
    Thanked 2 Times in 2 Posts
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Thread safe initialization of const variable in header file

    Hi,
    I'm using c++11 and I wonder if the initialization of the constant variable "Andrew" is thread safe in this code:

    Qt Code:
    1. //some_file.h
    2. namespace ns {
    3.  
    4. struct Person {
    5. const int id;
    6. const QString name;
    7. };
    8.  
    9. const Person Andrew { 2, QStringLiteral("Some string") };
    10. }
    To copy to clipboard, switch view to plain text mode 

  2. #2
    Join Date
    Sep 2009
    Location
    Wroclaw, Poland
    Posts
    1,394
    Thanked 342 Times in 324 Posts
    Qt products
    Qt4 Qt5
    Platforms
    MacOS X Unix/X11 Windows Android

    Default Re: Thread safe initialization of const variable in header file

    You probably want to declare Andrew as "extern" variable and define it in some .cpp file - now you will have one Andrew per every file in which you include your header:
    Qt Code:
    1. namespace ns {
    2.  
    3. struct Person {
    4. const int id;
    5. const QString name;
    6. };
    7.  
    8. extern const Person Andrew;
    9. }
    10.  
    11. // some.cpp
    12. #include "some_file.h"
    13. const ns::Person ns::Andrew = { 2, QStringLiteral("Some string") };
    To copy to clipboard, switch view to plain text mode 

    Such global data will be initialized before entering main(), so there will be no multiple threads trying to access Andrew at this point.
    As a side note, if you want to be sure that something gets called exactly once, you can use std::call_once.

Similar Threads

  1. Replies: 8
    Last Post: 29th July 2012, 01:28
  2. Replies: 5
    Last Post: 7th February 2012, 22:13
  3. Replies: 5
    Last Post: 9th January 2012, 22:00
  4. Debugging and variable initialization
    By fullmetalcoder in forum General Programming
    Replies: 0
    Last Post: 17th February 2009, 18:24
  5. Simple Question on Variable initialization
    By Naveen in forum Qt Programming
    Replies: 3
    Last Post: 17th March 2006, 11:01

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
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.