Static problem with initialization order in C ++

This is another variation of the old theme: the order of initialization of static objects in different translation units is not defined.

Below is a stripped-down example of my specific scenario. classes G and F are non-POD types. F depends on G, it makes sense that to build an instance of F, you need a certain number of instances of G. (For example, F may be the message that the application issues, and instances of G will be components of such messages.)

G.hpp

#ifndef G_HPP
#define G_HPP

struct G
{
    G() {} // ...
};

inline G operator+(G, G) { return G(); }

#endif

Gs.hpp

#ifndef GS_HPP
#define GS_HPP

#include "G.hpp"

extern const G g1;
extern const G g2;
extern const G g3;
extern const G g4;
extern const G g5;
extern const G g6;
extern const G g7;
extern const G g8;
extern const G g9;

#endif

Gs.cpp

#include "Gs.hpp"

const G g1;
const G g2;
const G g3;
const G g4;
const G g5;
const G g6;
const G g7;
const G g8;
const G g9;

F.hpp

#ifndef F_HPP
#define F_HPP

#include "G.hpp"

struct F
{
    F(G) {} // ...
};

#endif

Fs.hpp

#ifndef FS_HPP
#define FS_HPP

#include "F.hpp"

extern const F f1;
extern const F f2;
extern const F f3;

#endif

Fs.cpp

#include "Fs.hpp"
#include "Gs.hpp"

const F f1(g1 + g2 + g3);
const F f2(g4 + g5 + g6);
const F f3(g7 + g8 + g9);
Constructor

F takes an argument that is the result of applying operator+to instances of G. Since instances of F and G are global variables, there is no guarantee that instances of G have been initialized when the constructor of F needs them.

, Gs Fs , , G , F .

0
3

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.15.

, .

// Gs.hpp
const G & g1();

// Gs.cpp
const G & g1() {
  static const G* g1_ptr = new G();
  return *g1_ptr;
}

// Fs.cpp
const F & f1() {
  static const F* f1_ptr = new F(g1() + g2() + g3());
  return *f1_ptr;
}

, () s, #define, :

// Gs.hpp
const G & get_g1();
#define g1 (get_g1())
// Definition of get_g1() like g1() from prev. example
+1

extern . fN gN cpp .

0

Maybe a trick similar to the one used to initialize cinand friends' file buffers will work for you? (Read carefully <iostream>.)

0
source

All Articles