在C ++中,是否是编写在main()之前执行的代码的好方式? [英] In C++, Is it good form to write code that executes before main()?

查看:112
本文介绍了在C ++中,是否是编写在main()之前执行的代码的好方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全局声明的类的构造函数在输入main之前被调用。虽然这可能会让代码的新读者感到困惑,因为它很少做,这是不是一个坏主意?

The constructors of globally declared classes are invoked before main is entered. While this can be confusing to a new reader of the code because it is done so infrequently, is it necessarily a bad idea?

推荐答案

首先,它是全局数据,全局变量通常是一个坏事。
全局状态越多,对程序的理解就越难。

First, it's global data, and globals are usually a bad thing. The more global state you have, the harder it becomes to reason about your program.

其次,C ++不保证定义的静态对象的初始化顺序不同的翻译单元(.cpp文件) - 所以如果他们依赖于彼此,你可能会有麻烦。

Second, C++ doesn't guarantee intialization order of static objects defined in different translation units (.cpp files) -- so if they depend on one another, you might be in trouble.

这篇关于在C ++中,是否是编写在main()之前执行的代码的好方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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