PDA

View Full Version : Thread safe initialization of const variable in header file



kangaba
14th March 2014, 16:52
Hi,
I'm using c++11 and I wonder if the initialization of the constant variable "Andrew" is thread safe in this code:




//some_file.h
namespace ns {

struct Person {
const int id;
const QString name;
};

const Person Andrew { 2, QStringLiteral("Some string") };
}

stampede
19th March 2014, 21:53
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:


namespace ns {

struct Person {
const int id;
const QString name;
};

extern const Person Andrew;
}

// some.cpp
#include "some_file.h"
const ns::Person ns::Andrew = { 2, QStringLiteral("Some string") };



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 (http://en.cppreference.com/w/cpp/thread/call_once).