C ++常量的最佳实践 [英] C++ Best practices for constants
问题描述
我有一堆常量,我想在我的代码的不同部分访问,但我想要作为一个整体容易访问:
静态const bool doX = true;
static const bool doY = false;
static const int maxNumX = 5;
等。
所以我创建了一个名为constants.h的文件,并将它们全部保存在那里,并将它包含在任何需要知道常数的文件中。
问题是,这对于编译时是可怕的,因为每次更改常量时,所有需要重新构造constant.h引用的文件。 (另外,根据我的理解,因为它们是静态的,我每次在一个新的.cpp中包含constants.h时,会在代码中生成一个doX / doY / maxNumX的副本,导致编译后的KB空间浪费千字节EXE - 有什么办法看到这个吗?)。
所以,我想要一个解决方案。
有没有建议?
顺便提一句,不要担心大小增加:对于整数类型,常量可能直接内联在生成的机器代码中。
最后, static
不是必需的,因为默认情况下 const
是C ++中的 static
。
I have a whole bunch of constants that I want access to in different parts of my code, but that I want to have easy access to as a whole:
static const bool doX = true;
static const bool doY = false;
static const int maxNumX = 5;
etc.
So I created a file called "constants.h" and stuck them all in there and #included it in any file that needs to know a constant.
Problem is, this is terrible for compile times, since every time I change a constant, all files that constants.h reference have to be rebuilt. (Also, as I understand it, since they're static, I'm generating a copy of doX/doY/maxNumX in code every time I include constants.h in a new .cpp, leading to kilobytes of wasted space in the compiled EXE -- is there any way to see this?).
So, I want a solution. One that isn't "declare constants only in the files that use them", if possible.
Any suggestions?
The only alternative is to make your constants extern
and define them in another .cpp
file, but you'll lose potential for optimization, because the compiler won't know what value they have when compiling each .cpp`.
By the way, don't worry about the size increase: for integral types your constants are likely to be inlined directly in the generated machine code.
Finally, that static
is not necessary, since by default const
global variables are static
in C++.
这篇关于C ++常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!