问题描述
我喜欢使用 -Wsuggest-final-types
和 -Wsuggest-final-methods
,以便在可能使用final
关键字允许编译器更积极地进行优化的机会时得到警告.
I like compiling my code using -Wsuggest-final-types
and -Wsuggest-final-methods
in order to be warned about opportunities where the final
keyword could be used to allow the compiler to optimize more aggressively.
有时候,建议是不正确的-例如,我有一个Base
类,带有一个virtual ~Base()
析构函数,该析构函数在另一个项目中被多态使用,而gcc建议我将Base
标记为.
Sometimes, though, the suggestions are incorrect - for example, I have a class Base
with a virtual ~Base()
destructor that is used polymorphically in another project, and gcc suggests me that Base
could be marked as final
.
是否可以干净地"告诉编译器Base
是多态使用的,不应将其标记为final
?
Is there a way to "cleanly" tell the compiler that Base
is used polymorphically and should not be marked as final
?
我能想到的唯一方法是使用#pragma
指令,但是我发现它使代码混乱且难以阅读.
The only way I can think of is using #pragma
directives, but I find it makes the code cluttered and hard to read.
理想情况下,我正在寻找可以在类/方法声明之前/之后添加的non-final
关键字或属性.
Ideally, I'm looking for a non-final
keyword or attribute that can be prepended/appended to the class/method declaration.
推荐答案
我想出了一个我真的不喜欢的基于宏的解决方案,但是它解决了这个问题.
I came up with a macro-based solution that I really don't like, but it solves the problem.
#define MARK_NONFINAL_CLASS(base) \
namespace SOME_UNIQUE_NAME \
{ \
struct [[unused]] temp_marker final : base \
{ \
}; \
}
#define MARK_NONFINAL_METHOD(base, return_type, method) \
namespace SOME_UNIQUE_NAME \
{ \
struct [[unused]] temp_marker final : base \
{ \
inline return_type [[unused]] method override {} \
}; \
}
用法:
class Base
{
virtual ~Base()
{
}
virtual int a(float f)
{
}
virtual void b(double)
{
}
};
MARK_NONFINAL_CLASS(Base)
MARK_NONFINAL_METHOD(Base, int, a(float))
MARK_NONFINAL_METHOD(Base, void, b(double))
这篇关于彻底禁止gcc的“最终"建议警告("-Wsuggest-final-types"和"-Wsuggest-final-methods")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!