我有seen它写道:
The static initializer is executed before the first invocation of the containing function; the initializer expression must be a compile-time constant.
考虑一下:
void func(){
static float tr=((float) rand() / (RAND_MAX));
}
tr
依赖于运行时函数 rand()
。我不认为 rand()
的值在编译时是已知的,是吗?然而,这在 C++ 中编译得很好,很多答案/文献表明 C 行为在这方面与 C++ 相同。
最佳答案
在 C++ 中,局部静态初始化是在第一次进入作用域时执行的,表达式根本不需要是常量。您可以调用任何您喜欢的函数。例如,单例的常见模式是:
MySingleton& get_instance() {
static MySingleton s;
return s;
}
只有当(并且如果)调用 get_instance
函数时才会构造实例。使用 C++11,您甚至可以保证如果 get_instance
可能同时从多个线程调用,因为编译器将添加所需的锁定逻辑,这不会有问题。
在 C 中情况有所不同,静态初始化由加载程序在程序启动之前执行,您只能使用常量表达式,因此您问题中的代码无效(您不能调用 rand
)。
关于c++ - 成员函数内部的静态初始值设定项需要编译时常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251395/