By using godbolt, I can verify that clang++ and gcc++ are able to optimize out vtable when single type pattern is not used with static keyword.
#include <iostream>
class ISquare
{
public:
virtual int square(int num) const;
int field;
};
class Square final : public ISquare
{
public:
int inline square(const int num) const override final
{
return (num * num);
}
};
int main(const int count, char**)
{
// compiler is not able to optimize vtable away if static keyword in sq
static Square sq;
const ISquare& s = sq;
//const Square& s = Square(); // OK compiler is smart (eliminated vtable)
//const ISquare& s = Square(); // OK compiler is smart (eliminated vtable)
std::cout << s.field << '\n';
const auto r = s.square(count);
return r;
}
So if the code base relies heavily on singleton pattern where a method or free function returns a reference to instance that is not in local scope, then vtable elimination does not work as expected.
Following flags were used to compile
-std=c++11 -Os -fno-rtti -fno-exceptions -fdata-sections -fomit-frame-pointer -ffunction-sections -Wl,--gc-sections