I.2: Avoid non-​​const​​ global variables(避免非常数全局变量)

Reason(原因)

Non-​​const​​ global variables hide dependencies and make the dependencies subject to unpredictable changes.

非常数全局变量会隐藏依赖关系并导致依赖对象不可预知地被修改。

Example(示例)


 


 

struct Data {    // ... lots of stuff ...} data;            // non-const data
void compute() // don't{ // ... use data ...}
void output() // don't{ // ... use data ...}

Who else might modify ​​data​​?

还有谁会修改data?

译者注:全局变量可以被任何代码看到,也就可能被任何代码修改。如果变量命名时没有特殊的规则,这种问题就会更加难以解决。

Note(注意)

Global constants are useful.

全局常量是有用的。

Note(注意)

The rule against global variables applies to namespace scope variables as well.

针对全局变量的规则同样适用于命名空间范围的变量。

Alternative: If you use global (more generally namespace scope) data to avoid copying, consider passing the data as an object by reference to ​​const​​. Another solution is to define the data as the state of some object and the operations as member functions.

可选项:如果你使用全局(更普遍的情况是命名空间范围)数据来避免拷贝,考虑通过一个const类型的参照进行传递。另一个解决方案是将数据定义成某些对象的状态并将操作定义为成员函数。

译者注:第一种情况时,使用const参照的代码无法改写全局变量的内容,这样就可以限制对全局变量的修改;第二种情况可以通过成员函数控制和检查针对全局数据的修改。

 

Warning: Beware of data races: If one thread can access nonlocal data (or data passed by reference) while another thread executes the callee, we can have a data race. Every pointer or reference to mutable data is a potential data race.

警告:小心数据竞争。如果两个线程访问同一个数据(可以是全局的或者或者通过参照传递的),就可能出现数据竞争。每一个指向可修改数据的指针或者引用都可能发生数据竞争。

Note(注意)

You cannot have a race condition on immutable data.

你没有办法让不可修改的数据发生数据竞争。

 

References: See the rules for calling functions.

参考:参考函数调用规则。

Note(注意)

The rule is "avoid", not "don't use." Of course there will be (rare) exceptions, such as ​​cin​​​, ​​cout​​​, and ​​cerr​​.

这条准则是“避免”而不是“禁止使用”。当然存在(很少)例外情况。例如:cin,cout和cerr等。

以译者注:“避免”可以理解为如果可能就不用。

 

Enforcement(实施建议)

(Simple) Report all non-​​const​​ variables declared at namespace scope.

(简易)报告所有定义在命名空间范围的非常数变量。

 

觉得本文有帮助,欢迎点赞并分享给更多的朋友!

阅读更多更新文章,请关注微信公众号【面向对象思考】