c++ - 部分初始化其他模块中定义的变量

标签 c++ optimization compiler-construction static initialization

我正在考虑一个特定的解决方案,我想初始化在其他模块中定义的数组的一个单元格(会有很多模块初始化一个表)。在运行 main 之前不会读取数组(因此静态初始化顺序没有问题)。

我的方法:

/* secondary module */

 extern int i[10]; // the array

 const struct Initialize {
  Initialize() { i[0] = 12345; }
 } init;


/* main module */

 #include <stdio.h>


 int i[10];

 int main()
 {
  printf("%d\n", i[0]); // check if the value is initialized
 }

编译器不会删除 init 常量,因为构造函数有副作用。我对吗?机制好吗?在 GCC (-O3) 上一切正常。

//编辑
在现实世界中会有很多模块。 我想避免一个额外的模块,一个将收集所有次要初始化例程的中心位置(为了更好的可扩展性)。因此,每个模块触发自己的初始化很重要。

最佳答案

这适用于 MSVC 编译器,但不适用于 GNU C++(至少对我而言)。 GNU 链接器将去除所有未在编译单元外使用的符号。我只知道一种保证这种初始化的方法——“初始化一次”的惯用语。例如:

初始化一次.h:

template <typename T>
class InitOnce
{
    T *instance;
    static unsigned refs;
public:
    InitOnce() {
        if (!refs++) {
            instance = new T();
        }
    }

    ~InitOnce() {
        if (!--refs) {
            delete instance;
        }
    }
};
template <typename T> unsigned InitOnce<T>::refs(0);

单元.h:

#include "init_once.h"

class Init : public InitOnce<Init>
{
public:
    Init();
    ~Init();
};
static Init module_init_;

二级.cpp:

 #include "unit.h"
 extern int i[10]; // the array

 Init::Init()
 {
     i[0] = 12345;
 }
 ...

关于c++ - 部分初始化其他模块中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3187770/

相关文章:

c++ - vector 索引的 uintmax_t

c++ - 由于 ID3D11Buffer 而导致访问冲突

c++ - 函数原型(prototype)设计 - C++

php - 从 PHP 更新 MYSQL 语句

compiler-construction - 自学编译器类(class)/好的入门编译器书籍?

python - 简单的解析器,但不是计算器

c++ - 在线程之间解析 OpenCV 帧

c# - 制作不同数组的优化算法

c - 算法优化同时

c++ - 奇怪的编译错误 C++ "undefined reference"& "relocation truncated"