Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static data member initialization order

Tags:

c++

Consider the code below in a single translation unit:

class C {
private:

    struct Init {

        Init() {
            /* compute data once here */
        }
    };
    static const Init& i;
    static int data[];
public:
    /* interface for reading data */
};

const C::Init& C::i = Init();
int C::data[200];
  1. Is C::i always initialized after C::data no matter the order of the definition of both?
  2. Is this solution the most elegant one for computing static data once?
like image 232
Martin Avatar asked Aug 24 '26 13:08

Martin


1 Answers

int C::data[200] is zero-initialized, which means that it is statically initialized. Static initialization comes before dynamic initialization. Since C::Init::Init() is not a constant expression, C::i is dynamically initialized, necessarily after C::data.

See 3.6.2 for details.

A bootleg quote:

Variables with static storage duration [...] shall be zero-initialized before any other initialization takes place. [...] Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place.

like image 76
Kerrek SB Avatar answered Aug 27 '26 05:08

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!