在静态初始化期间运行代码

Running code during static initialization

本文关键字:运行 代码 静态 初始化      更新时间:2023-10-16

在我的程序中,我有以下代码:

struct C {
static bool Register();
// other methods
private:
// instance data
};
bool Register() {
// perform registration
return true;
}
// - - - -
static bool const registered = C::Register();

这是可行的,但cppcheck抱怨说,因为它发现registered在写入后从未被读取。

对于返回void的函数,是否有方法实现相同的效果(在静态初始化期间调用函数(?

struct C {
static bool Register();
// other mnethods
private:
// instance data
};
void Register() {
// perform registration
}
class Registrator
{
public:
Registrator() {Register();}
};
static Registrator registrator;

我不理解你的类的设计。。。为什么要有一个调用外部Register()函数的注册类。。。为什么不像一样

// C can be a singleton
struct C {
C() { Register(); }
static bool Register();
// other mnethods
private:
// instance data
};
static C registrator;

如果C是一个singletong,它可能会像:

// C can be a singleton
struct C {
C& instance() { static C inst; return inst; }
// other mnethods
private:
C() { Register(); }
bool Register();
private:
// instance data
};
static C& registration = C::instance();