【发布时间】:2015-02-27 00:25:15
【问题描述】:
在 C++11 中定义简单常量值的最佳方法是什么,这样就不会产生运行时损失?例如:(无效代码)
// Not ideal, no type, easy to put in wrong spot and get weird errors
#define VALUE 123
// Ok, but integers only, and is it int, long, uint64_t or what?
enum {
Value = 123
};
// Could be perfect, but does the variable take up memory at runtime?
constexpr unsigned int Value = 123;
class MyClass {
// What about a constant that is only used within a class, so
// as not to pollute the parent namespace? Does this take up
// memory every time the class is instantiated? Does 'static'
// change anything?
constexpr unsigned int Value = 123;
// What about a non-integer constant?
constexpr const char* purpose = "example";
std::string x;
std::string metadata() { return this->x + (";purpose=" purpose); }
// Here, the compiled code should only have one string
// ";purpose=example" in it, and "example" on its own should not
// be needed.
};
编辑
因为有人告诉我这是一个无用的问题,因为它背后没有背景,这就是背景。
我正在定义一些标志,以便我可以做这样的事情:
if (value & Opaque) { /* do something */ }
Opaque 的值在运行时不会改变,所以它只在编译时才需要,让它出现在我的编译代码中似乎很愚蠢。这些值也在一个循环中使用,该循环对图像中的每个像素运行多次,所以我想避免运行时查找会减慢它(例如,在运行时检索常量值的内存访问。)这不是t 过早优化,因为该算法目前处理一张图像大约需要一秒钟,而且我通常有超过 100 张图像要处理,所以我希望它尽可能快。
既然人们说这是微不足道的,不用担心,我猜#define 是尽可能接近字面值,所以也许这是避免“过度思考”问题的最佳选择?我想普遍的共识是你只是希望没有人需要使用Opaque这个词或你想使用的其他常量?
【问题讨论】:
-
您确定您的内存如此紧张以至于 4 个字节会有所不同吗?
-
为什么大家总是这么说?然后你发布你想要的东西,你得到的只是风滚草,因为没有人能弄清楚你想要什么,除了一个人说你应该发布一个只有核心点的简单例子......叹息
-
@Brian:当然 4 个字节并不多,但是您是否会在代码周围留下未使用的变量?为什么要删除它们,可以禁用编译器警告,并且几个字节并不多:-P 当然,一个原因是,如果您在循环多次的算法中使用这些值,那么直接在代码中删除一个值每次访问时查找内存,使您的算法更快(尽管有编译器优化。)
-
是的,您应该发布一个仅包含核心点的简单示例,但这些核心点应该与现实有所关联。这个问题并不表示任何实际问题。它只是在没有实际定义任何约束的情况下征求意见,使其毫无用处!
-
好吧,我使用字段作为标志,例如
if (value & SomeFlag) { /* do something */ }。与其说if (pixel & 2),不如说if (value & Opaque),因为它更容易阅读,但Opaque的值在运行时不会改变。仅在编译时才需要它,并且仅仅因为我希望我的代码易于阅读而将其嵌入到我的可执行文件中似乎很愚蠢。它也在一个为每个像素运行多次的循环内,所以我想避免运行时查找会减慢它的速度。所以我追求最优雅的常量定义方式,重点关注新的 C++11/14 特性。
标签: c++ c++11 constants constexpr idioms