静态变量初始化? [英] Static variable initialization?

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

问题描述

我想知道在C,C ++和Java到底为什么静态变量默认被初始化为零?以及为什么这是不正确的局部变量?

I want to know why exactly static variables in C, C++ and Java are initialized by zero by default? And why this is not true for local variables?

推荐答案

为什么静态变量初始化确定性和局部变量有没有关系?

查看静态变量是如何实现的。 作为他们的内存在链接时分配,也链接时为他们提供的初始值。没有运行时开销。

See how the static variables are implemented. The memory for them is allocated at link time, and the initial value for them is also provided at link time. There is no runtime overhead.

在另一方面,局部变量的存储在运行时分配的。堆栈有增长。你不知道什么是那里。如果你愿意,你可以清除内存(零),但在可能发生的运行时开销。 C ++的理念是您不支付的东西你不使用,所以它不为零默认情况下该内存。

On the other hand, the memory for local variables is allocated at run time. The stack has to grow. You don't know what was there before. If you want, you can clear that memory (zero it), but that would incur a runtime overhead. The C++ philosophy is "you don't pay for things you don't use", so it doesn't zero that memory by default.

OK,但为什么静态变量初始化为零,而不是一些其他的价值?

好吧,你通常想要做的与该变量的东西。但你怎么知道它是否已初始化?你可以创建一个静态布尔变量。但随后它也有可靠地初始化为某物(preferably假)。 如何对一个指针?你宁愿想把它初始化为NULL比一些随机的垃圾。如何约一个struct /记录?它里面的一些其他的数据成员。这是有道理的所有的人都初始化为它们的默认值。但是,为了简单起见,如果您使用初始化为0的策略,你不必检查个人会员和检查它们的类型。 您可以只初始化整个内存区域为0。

Well, you generally want to do something with that variable. But then how do you know if it has been initialized? You could create a static boolean variable. But then it also has to be reliably initialized to something (preferably false). How about a pointer? You'd rather want it initialized to NULL than some random garbage. How about a struct/record? It has some other data members inside. It makes sense to initialize all of them to their default values. But for simplicity, if you use the "initialize to 0" strategy, you don't have to inspect the individual members and check their types. You can just initialize the entire memory area to 0.

这是不是一个真正的技术要求。如果默认值是其他的东西比0,但仍确定性初始化的语义仍然可以被认为是理智的。不过,应该说价值是什么?你可以很容易解释为什么使用0(尽管其实这听起来略显武断),但解释-1或1024似乎更加困难(特别是变量可能不是大到足以容纳该值,等等)。

This is not really a technical requirement. The semantics of initialization could still be considered sane if the default value is something other than 0, but still deterministic. But then, what should that value be? You can quite easily explain why 0 is used (although indeed it sounds slightly arbitrary), but explaining -1 or 1024 seems to be even harder (especially that the variable may not be large enough to hold that value, etc).

和你总是可以明确地初始化变量。

And you can always initialize the variable explicitly.

和你总是有C ++标准第8.5.6它说静态存储持续时间的每个对象应在程序启动时初始化为零。

And you always have paragraph 8.5.6 of the C++ standard which says "Every object of static storage duration shall be zero-initialized at program startup".

有关更多信息,请参考这些其他问题:

For more info, please refer to these other questions:

这篇关于静态变量初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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