Why should const members be static for proper optimization?

Given:

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(); }

Compiled output gives a memory sample to read the value xin fn0(), while adding staticresults in literal 5becoming inlined in fn1(). The implication is that the caller get()can be optimized as if it were using a constant instead get(), only when the integer constant is static.

I have more difficult situations when it staticdoes not fit. Derived classes are initialized with xdifferent values ​​through the constructor; but for each of these classes xis a constant, and these methods of the class can be optimized, as in the previous case static, if only get()evaluated by a true constant.

In fact, my most common case is with link initialization in the base class:

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(); }

Here, if get()evaluated directly in the Bar::minside getget(), I would avoid the pointer level. This is not possible if it xis static.

I don’t understand why staticit is necessary to enable this optimization.

+4
source share
1 answer

A static const int member initialized in-class - , .

const int , , . , -, mem. , , , :

class Foo {
    const int x = 5;
  public:
    inline int get() { return x; }
    Foo() = default;
    Foo(int x) : x(x) {}
};

Foo::x 5, , - , Foo::Foo(int). , , :

class Foo {
  public:
    const int x = 5;
    inline int get() { return x; }
};

:

Foo f {42};
// f.x is 42

Foo, , , , Foo::x 5, , Foo::x - . , ​​.

+3

All Articles