tags:

views:

465

answers:

4

I have been using anonymous namespaces to store local data and functions and wanted to know when the data is initialized? Is it when the application starts in the same way as static data or is it compiler dependent? For example:

// foo.cpp
#include "foo.h"

namespace {

const int SOME_VALUE = 42;

}

void foo::SomeFunc(int n)
{
    if (n == SOME_VALUE)
    {
        ...
    }
}

The question arises out of making some code thread-safe. In the above example I need to be certain that SOME_VALUE is initialized before SomeFunc is called for the first time.

+1  A: 

In this particular case (a global variable that is const) the variable is "initialized" at compile time.

SOME_VALUE is always equal to 42.

In fact, most (all?) compiler will actually compile this as if it was hardcoded :

void foo::SomeFunc(int n)
{
    if (n == 42)
    {
        ...
    }
}
Mathieu Pagé
A: 
MadKeithV
+1  A: 

Namespaces have nothing to do with the time of initialization. All that a namespace does is change names that belong to it.

Nemanja Trifunovic
+3  A: 

C++ Standard, 3.6.2/1 :

Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.

This effectively means, even when another translation unit calls your SomeFunc function from outside, your SOME_VALUE constant will always be correctly initialized, because it's initialized with a constant expression.

The only way for your function being called early (before main) is while initializing an object with dynamic initialiation. But by that time, according to the standard quote, the initialization of your POD variable is already done.

Johannes Schaub - litb