class Foo { const int x = 5; public: inline int get() { return x; } };
class Bar { static const int x = 5; public: inline int get() { return x; } };
int fn0(Foo& f) { return f.get(); }
int fn1(Bar& b) { return b.get(); }
编译的输出给出了一个存储器提取在fn0()
读取的x
的值,而添加static
结果字面5
被内联在fn1()
。暗示的是get()
的调用者可以被优化,就好像它仅在整数常量是静态时使用常量来代替get()
。
我有更复杂的情况,其中static
不合适。派生类通过构造函数将x
初始化为不同的值;但对于每个类x
是一个常数,那些类的方法可以优化,如前static
的情况下,如果只有get()
评估真正的常数。
其实,我最常见的情况是在基类中引用的初始化:
class Foo { int& x; public: Foo(int& init) : x(init) {} inline int get() { return x; } };
class Bar : public Foo { int m; public: Bar() : Foo(m) {} inline int getget() { return get(); };
int fn1(Bar& b) { return b.getget(); }
这里,如果get()
直接评估,以Bar::m
getget()
内我会避免间接指针的水平。如果x
是静态的,这将不可能。
我不清楚为什么static
是必要的,以允许此优化。
因此,简而言之,有一个答案指出'静态'成员可以放置在只读段中,因此它们的const属性由硬件强制执行。即使这不是根据规范的答案,我确实认为这是值得注意的。 – sh1