在静态初始化期间运行代码
Running code during static initialization
在我的程序中,我有以下代码:
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();
相关文章:
- 如何在linux终端中同时编译和运行c++代码
- 尝试用java代码编译和运行c++代码
- 不同/较旧的处理器运行c++代码的方式是否不同
- 无法在 geany 上运行代码。无法执行构建命令
- 运行代码时,c++ 会终止进程
- 编译多个C++文件.调用二进制文件以运行代码
- 分段故障 运行C++代码时出现 SIGSEGV
- 如何分析在 Windows 上运行C++代码?
- 编译器资源管理器(godbolt)如何安全地运行代码?
- 如何在 vim (windows) 中编译和运行 c++ 代码
- 无法在 Visual Studio 代码中生成和运行 C++ 代码
- 连续运行C++代码和 Python 代码
- 在静态初始化期间运行代码
- C++ .我正在尝试通过使用开关内的数组来获取用户输入,但是当我运行代码时,它显示分段错误?
- 我最近更改了编译器路径以运行 c++ 代码,但现在我无法运行任何 python 代码。我该如何解决这个问题?
- 如何在Visual Studio Code的终端内运行C++代码?
- 在注入的 Dll 的 DllMain 中运行代码导致注入超时
- 并行和顺序运行代码时会产生不同的结果
- 运行代码时C++错误
- 在 CortexM0 中从 RAM 运行代码时出现硬故障