Static initialization order in a class hierarchy

I recently became painfully aware of Fiasco 's static initialization order . I am wondering, but if the rule is that the "initialization order is undefined for translation units" is still performed for the static members in the parent class, which are needed by the static members in the child class.

For example, let's say that we have (except, for brevity, all #guards and included)

// a.h
class A {
    static int count;
    static int register_subclass();
};

// a.cpp
int A::count = 0;
int A::register_subclass() {
    return count ++;
}

And then subclasses A,

// b.h
class B : public A {
    static int id;
};

// b.cpp
int B::id = A::register_subclass();

There are two translation units with static objects in one, depending on the static objects in the other during initialization ... it looks like it could be an instance of the static initialization order fiasco.

My question is: is it really safe?

, , , B::id , A::count, , ? A , , , , , , undefined.

+4
2

, . , A B. .

:

// a.h
class A {
private:
    static int& count();
protected:
    static int register_subclass();
};

// a.cpp
int& A::count() {
    static int count = 0;
    return count;
}

int A::register_subclass() {
    return count()++;
}

// b.h
class B : public A {
public:
    static int id;
};

// b.cpp
int B::id = A::register_subclass();

: , ,

[3.6.2] , . , , A::count , , B::id.

, .

, A::register_subclass . , .

+3

, , , " undefined " - , .

, .

, (, , ), ; / .

0

Source: https://habr.com/ru/post/1612091/


All Articles