C ++中的静态初始化顺序问题 [英] Static initialization order issue in C++

查看:184
本文介绍了C ++中的静态初始化顺序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个旧主题的另一个变体:
静态对象在不同翻译单元中的初始化顺序未定义。

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

我的特定场景的下降示例。
类G和F是非POD类型。 F取决于G是对
构造F的一个实例的感觉,你需要一些数量的
G.实例(例如,F可以是应用程序发出的一些消息,
实例的G将是此类邮件的组成部分。)

Below is a stripped-down example of my particular scenario. The classes G and F are non-POD types. F depends on G is the sense that to construct an instance of F you need some number of instances of G. (For example, F could be some message an application emits, and instances of G would 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 / p>

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 / p>

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 / p>

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);

F的构造函数接受一个参数,它是应用
因为F和G的实例是
全局变量,所以不能保证G的实例具有
在F的构造函数被初始化时需要他们。

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

这里的特殊性是在
位置有许多G和F,我想尽可能多地保留语法关闭
到上面的代码,同时仍然执行一个
G每当一个F需要它的构造。

The particularity here is that there are many Gs and Fs all over the place, and I would like to keep the syntax as much as possibly close to the code posted above, while still enforcing the construction of a G whenever an F needs it.

推荐答案

http://www.parashift.com/

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

将全局对象更改为在首次使用时构造对象的函数。

Change your global objects into functions which construct the object on first use.

// 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;
}

或者如果你真的不能再添加额外的(),使用一些 #define s隐藏它们:

Or if you really can't stand adding the extra ()s, use some #defines to hide them:

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

这篇关于C ++中的静态初始化顺序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆