我有一些全局变量,它们的构造函数依赖于不同翻译单元中的其他全局变量。我的理解是,全局变量的初始化顺序是未指定的,因此这是不安全的。
我该如何确保我需要的全局变量在首次访问时最晚被初始化?例如,如果我在函数中创建一个静态变量,并调用该函数以获取引用,那么它是否总是在第一次执行函数时初始化?
我有一些全局变量,它们的构造函数依赖于不同翻译单元中的其他全局变量。我的理解是,全局变量的初始化顺序是未指定的,因此这是不安全的。
我该如何确保我需要的全局变量在首次访问时最晚被初始化?例如,如果我在函数中创建一个静态变量,并调用该函数以获取引用,那么它是否总是在第一次执行函数时初始化?
std::cout
及其相关函数相同的方法,它被称为Schwarz Counter或Nifty Counter。libstdc++
的 ios_base.h
头文件:// 27.4.2.1.6 Class ios_base::Init
// Used to initialize standard streams. In theory, g++ could use
// -finit-priority to order this stuff correctly without going
// through these machinations.
class Init
{
friend class ios_base;
public:
Init();
~Init();
private:
static _Atomic_word _S_refcount;
static bool _S_synced_with_stdio;
};
并包含iostream
头文件:
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
extern istream cin; /// Linked to standard input
extern ostream cout; /// Linked to standard output
extern ostream cerr; /// Linked to standard error (unbuffered)
extern ostream clog; /// Linked to standard error (buffered)
// For construction of filebuffers for cout, cin, cerr, clog et. al.
static ios_base::Init __ioinit;
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
并进入ios_init.cc
:
ios_base::Init::Init()
{
if (__gnu_cxx::__exchange_and_add_dispatch(&_S_refcount, 1) == 0)
{
// Standard streams default to synced with "C" operations.
_S_synced_with_stdio = true;
new (&buf_cout_sync) stdio_sync_filebuf<char>(stdout);
new (&buf_cin_sync) stdio_sync_filebuf<char>(stdin);
new (&buf_cerr_sync) stdio_sync_filebuf<char>(stderr);
// The standard streams are constructed once only and never
// destroyed.
new (&cout) ostream(&buf_cout_sync);
new (&cin) istream(&buf_cin_sync);
new (&cerr) ostream(&buf_cerr_sync);
new (&clog) ostream(&buf_cerr_sync);
cin.tie(&cout);
cerr.setf(ios_base::unitbuf);
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 455. cerr::tie() and wcerr::tie() are overspecified.
cerr.tie(&cout);
// NB: Have to set refcount above one, so that standard
// streams are not re-initialized with uses of ios_base::Init
// besides <iostream> static object, ie just using <ios> with
// ios_base::Init objects.
__gnu_cxx::__atomic_add_dispatch(&_S_refcount, 1);
}
}
ios_base::Init::~Init()
{
// Be race-detector-friendly. For more info see bits/c++config.
_GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_S_refcount);
if (__gnu_cxx::__exchange_and_add_dispatch(&_S_refcount, -1) == 2)
{
_GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_S_refcount);
// Catch any exceptions thrown by basic_ostream::flush()
__try
{
// Flush standard output streams as required by 27.4.2.1.6
cout.flush();
cerr.flush();
clog.flush();
}
__catch(...)
{ }
}
}
// DynamicInitializer.h
template<class T>
struct DynamicInitializer
{
// These members have to be POD types to be zero-initialized at static initialization phase
// prior to the dynamic initialization phase which invokes constructors of global objects.
static T* instance_;
static unsigned ref_count_;
DynamicInitializer() {
if(!ref_count_++)
instance_ = new T;
}
~DynamicInitializer() {
if(!--ref_count_)
delete instance_;
}
operator T&() const { return *instance_; }
T* operator->() const { return instance_; }
DynamicInitializer(DynamicInitializer const&) = delete;
DynamicInitializer& operator=(DynamicInitializer const&) = delete;
};
template<class T>
unsigned DynamicInitializer<T>::ref_count_ = 0;
template<class T>
T* DynamicInitializer<T>::instance_ = 0;
使用方法:
// MyLogger.h
struct MyLogger
{
void log(char const*);
};
// const makes static storage.
DynamicInitializer<MyLogger> const my_global_logger;
MyLogger.h
时,my_global_logger
都保证在第一次使用之前进行初始化,例如:my_global_logger->log("hello");
。