通过使用Godbolt,我可以验证当静态关键字不使用单一类型模式时,clang ++和gcc ++能够优化vtable。
#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;
}
因此,如果代码库严重依赖于单例模式,其中方法或自由函数返回对不在本地范围内的实例的引用,则vtable消除将无法正常工作。
使用以下标志进行编译
-std=c++11 -Os -fno-rtti -fno-exceptions -fdata-sections -fomit-frame-pointer -ffunction-sections -Wl,--gc-sections