Use short and definable virtual optimization methods?

I'm just wondering if most compilers can do the following optimization

class A
{
    virtual void f() { m = 5; }
    void g() { f(); }
    int m;
};

f()is a virtual function and therefore not built-in. However, can the compiler be optimized g()for the call f()as inline, since the definition f()is short and accessible?

+4
source share
2 answers

I do not think they can. That's why:

class B : public A
{
   virtual void f() {}
}

B b;
b.g(); // This must result in B::f() getting called.
+2
source

can the compiler optimize g () to call f () as inline, since the definition of f () is short and accessible?

. g() , A::g() , A::f(). A, g() , , A* A& .

f(), " ", , , f(): , - f() .

struct B : A { void f() { ... } }
B b;
b.g();  // g() and B::f() may be inlined
A* p = &b;
p->g(); // g() and B::f() may be inlined (latter iff optimiser tracks p addressing a B)
p = opaque_factory();  // definition not known to compiler
p->g(); // equivalent to p->f();, g() inline, f() dispatched virtually / not inline.

void x(A* p) { p->g(); }  // g() may be inlined
x(p); // iff x is inlined, g() and B::f() may be too - per p->g() call above
      // iff x is out-of-line, and compiler doesn't do full-program analysis and find
      //    it only ever called for a specific runtime type (unlikely if not a
      //    single-translation-unit program), then dispatch to f() can not be inlined
      //    and must be virtual

, g() (.. ) , , g() .

g() ( , / .., ) : , ​​ ().

+5

Source: https://habr.com/ru/post/1535667/


All Articles