Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How static local POD constants are initialized? Lazily or not?

Tags:

c++

POD means primitive data type without constructor and destructor.

I am curious, how compilers handle lazy initialization of POD static local variables. What is the implication of lazy initialization if the function are meant to be run inside tight loops in multithreaded applications? These are the possible choices. Which one is better?

void foo_1() {
    static const int v[4] = {1, 2, 3, 4};
}

void foo_2() {
    const int v[4] = {1, 2, 3, 4};
}

How about this? No lazy initialization, but slightly clumsy syntax?

struct Bar
{
    static const int v[4];

    void foo_3()
    {
        // do something
    }
};

const int My::v[4] =  {1, 2, 3, 4};
like image 342
watson1180 Avatar asked Dec 22 '22 19:12

watson1180


2 Answers

In foo_1(), v is initialized sometime before main() starts. In foo_2(), v is created and initialized every time foo_2() is called. Use foo_1() to eliminate that extra cost.

In the second example, Bar::v is also initialized sometime before main().

like image 26
Niall C. Avatar answered Dec 31 '22 00:12

Niall C.


When a static variable is initialized with constant data, all compilers that I'm familiar with will initialize the values at compile time so that there is no run time overhead whatsoever.

If the variable isn't static it must be allocated on each function invocation, and the values must be copied into it. I suppose it's possible that the compiler might optimize this into a static if it's a const variable, except that const-ness can be cast away.

like image 107
Mark Ransom Avatar answered Dec 31 '22 02:12

Mark Ransom