成员函数内部静态初始化需要编译时常? [英] Static initializer inside member function require compile-time constant?

查看:179
本文介绍了成员函数内部静态初始化需要编译时常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到它写的是:

静态初始化器包含函数的第一次调用之前执行;初始化前pression必须是一个编译时间常数。

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 取决于运行时函数,兰特()。我不认为兰特()在编译时是已知的,是它的价值呢?然而,这个编译C ++和很多答案精细/文献表明,Ç的行为是一样的C ++在这方面。

tr depends on a runtime function, rand(). I don't think the value of rand() is known at compile time, is it? Yet this compiles fine in C++ and a lot of answers/literature indicate that C behavior is the same as C++ in this regard.

推荐答案

在C ++本地静态初始化进行第一次进入的范围和前pression并不需要是一个恒定的。你可以调用任何你喜欢的功能。单身常见的图案是例如:

In C++ a local static initialization is performed the first time the scope is entered and the expression doesn't need to be a constant at all. You can call any function you like. A common patter for singletons is for example:

MySingleton& get_instance() {
    static MySingleton s;
    return s;
}

在这里实例将建设只有当(如果)在 get_instance 函数被调用。随着C ++ 11你甚至保证不会有问题,如果 get_instance 可能是从多个线程调用在同一时间,因为编译器将添加需要锁定逻辑

where the instance will be constructed only when (and if) the get_instance function is called. With C++11 you're even guaranteed that there will be no problem if get_instance is possibly called from multiple threads at the same time as the compiler will add the needed locking logic.

在C语言中的东西是不同的,由加载程序启动之前进行静态初始化,你只能用不断的前pressions所以你的问题code是无效的(你不能叫兰特)。

In C things are different and static initialization is performed by the loader before program starts and you can only use constant expressions so the code in your question is not valid (you cannot call rand).

这篇关于成员函数内部静态初始化需要编译时常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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