未初始化变量的危害是什么? [英] What are the dangers of uninitialised variables?

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

问题描述

在我正在编写的程序中,我的.h文件中当前有几个未初始化的变量,所有这些变量都在运行时进行了初始化.但是,在Visual Studio中,每次执行此操作时都会警告我总是初始化成员变量",尽管这样做看起来似乎毫无意义.我很清楚,在未初始化时尝试使用变量会导致未定义的行为,但是据我所知,不这样做可以避免这种情况.我在俯视什么吗?

In a program I am writing I currently have several uninitialised variables in my .h files, all of which are initialised at run-time. However, in Visual Studio it warns me every time I do this to "Always initialise a member variable" despite how seemingly pointless it feels to do so. I am well aware that attempting to use a variable when uninitialised will lead to undefined behaviour, but as far as I know, this can be avoided by not doing so. Am I overlooking something?

谢谢.

推荐答案

如果不初始化变量并在零初始化)

These variables could contain any value if you don't initialize them and reading them in an uninitialized stated is undefined behavior. (except if they are zero initalized)

如果您忘记初始化其中的一个,而意外读取它会导致您希望它在当前系统配置上具有应有的值(由于未定义的行为),那么在执行以下操作后,程序的行为可能无法预测/无法预期系统更新,在其他系统上或在代码中进行更改时.

And if you forgot to initialize one of them, and reading from it by accident results in the value you expect it should have on your current system configuration (due to undefined behavior), then your program might behave unpredictable/unexpected after a system update, on a different system or when you do changes in your code.

这些错误很难调试.因此,即使您在运行时设置它们,也建议将它们初始化为已知值,以使您拥有一个行为可控的受控环境.

And these kinds of errors are hard to debug. So even if you set them at runtime it is suggested to initialize them to known values so that you have a controlled environment with predictable behavior.

有一些例外,例如如果您在声明变量后立即设置了该变量,并且无法直接对其进行设置,例如使用流运算符设置其值.

There are a few exceptions, e.g. if you set the variable right after you declared it and you can't set it directly, like if you set its value using a streaming operator.

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

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