在C/ c++中,全局变量像我的教授认为的那样糟糕吗?


当前回答

不,他们一点都不坏。你需要查看编译器生成的(机器)代码来做出判断,有时使用局部变量比使用全局变量要糟糕得多。还要注意,在局部变量上添加“static”基本上是使其成为全局变量(并产生真正的全局变量可以解决的其他丑陋问题)。“局部全局变量”尤其糟糕。

全局变量还可以让你完全控制内存的使用,这在局部变量中要困难得多。如今,这只在内存相当有限的嵌入式环境中才重要。在假定嵌入式环境与其他环境相同并假定编程规则全面相同之前,需要了解一些事情。

It is good that you question the rules being taught, most of them are not for the reasons you are being told. The most important lesson though is not that this is a rule to carry with you forever, but this is a rule required to honor in order to pass this class and move forward. In life you will find that for company XYZ you will have other programming rules that you in the end will have to honor in order to keep getting a paycheck. In both situations you can argue the rule, but I think you will have far better luck at a job than at school. You are just another of many students, your seat will be replaced soon, the professors wont, at a job you are one of a small team of players that have to see this product to the end and in that environment the rules developed are for the benefit of the team members as well as the product and the company, so if everyone is like minded or if for the particular product there is good engineering reason to violate something you learned in college or some book on generic programming, then sell your idea to the team and write it down as a valid if not the preferred method. Everything is fair game in the real world.

如果你遵循学校或书本上教给你的所有编程规则,那么你的编程生涯将非常有限。你很可能会生存下来,并拥有一个富有成效的事业,但你所能获得的环境的广度和宽度将是极其有限的。如果你知道规则是如何存在的,为什么会存在,并且能够捍卫它,那很好,如果你的理由只是“因为我的老师这么说”,那就不太好了。

请注意,这样的话题经常在工作场所被争论,并且将继续存在,随着编译器和处理器(以及语言)的发展,这些类型的规则也在发展,如果不捍卫你的立场,可能会被持不同意见的人教训一课,你就不会前进。

与此同时,那个说话声音最大或拿着最大棍子的人说什么,你就做什么(直到你是那个喊得最大、拿着最大棍子的人)。

其他回答

我通常对很少改变的值使用全局变量,如单例或动态加载库中函数的函数指针。在多线程应用程序中使用可变全局变量往往会导致难以跟踪错误,所以我尽量避免将其作为通用规则。

使用全局变量而不是传递参数通常更快,但如果您正在编写一个多线程应用程序(您现在经常这样做),它通常不会很好地工作(您可以使用线程静态,但性能收益是值得怀疑的)。

全局变量通常很糟糕,特别是当其他人正在处理相同的代码,并且不想花20分钟搜索变量被引用的所有位置时。添加修改变量的线程带来了一个全新的问题。

在单个翻译单元中使用匿名名称空间中的全局常量是很好的,在专业应用程序和库中无处不在。但是如果数据是可变的,并且/或者它必须在多个tu之间共享,那么您可能想要封装它——如果不是为了设计,那么也是为了任何人调试或使用您的代码。

是的,但是在停止使用全局变量的代码并开始编写使用全局变量的代码之前,您不会招致全局变量的成本。但成本依然存在。

换句话说,这是一种长期的间接成本,因此大多数人认为这并不坏。

在企业内的web应用程序中,可以用于在服务器上保存会话/窗口/线程/用户特定的数据,以优化和保存连接不稳定时的工作损失。如前所述,需要处理竞争条件。我们使用类的单个实例来获取这些信息,并且对其进行了仔细的管理。

如果您的代码有可能在最高法院审判期间被严格审查,那么您应该确保避免使用全局变量。

请看这篇文章: 漏洞百出的酒精测试仪代码反映了源代码审查的重要性

There were some problems with the style of the code that were identified by both studies. One of the stylistic issues that concerned the reviewers was the extensive use of unprotected global variables. This is considered poor form because it increases the risk that the program state will become inconsistent or that values will be inadvertently modified or overwritten. The researchers also expressed some concern about the fact that decimal precision is not maintained consistently throughout the code.

伙计,我敢打赌那些开发人员希望他们没有使用全局变量!