One interesting unusual use case I have found I described here. In short, by preventing inheritance from your int-like class, you buy yourself a possibility to replace it with a built-in type in the future releases of your library, without the risk of breaking your user's code.
But a more common example is devirtualization. If you mark your class as final, compiler can apply certain run-time optimizations. For instance,
struct Object {
virtual void run() = 0;
virtual ~Object() {}
};
struct Impl final : Object
{
void run() override {}
};
void fun(Impl & i)
{
i.run(); // inlined!
}
The call to i.run()
can be now inlined due to final
specifier. The compiler knows that vtable look-up will not be needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…