如何确保一个类没有虚方法?
我有一个类,其对象在共享内存中使用。因此,我必须确保它们没有虚拟方法(通过 vtable 调用时会导致程序崩溃)。
我想防止任何人意外地添加虚拟方法来违反此要求。理想情况下,如果类包含虚方法,编译器甚至会拒绝编译该类。
解决方案不一定需要符合标准,只要它们能够在 Apple 的 gcc-4.2 或 MSVC 上运行就足够了。
我怎样才能实现这个目标?
I have a class whose objects are used in shared memory. Therefore, I must be sure that they do not have virtual methods (which crash the program when called via vtable).
I would like to guard against anybody accidentally adding a virtual method in violation of this requirement. Ideally, the compiler would refuse to even compile the class if it contains virtual methods.
Solutions do not necessarily need to be standards compliant, it is sufficient if they work on Apple's gcc-4.2 or MSVC.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您创建了一个源模块,其中包含一个与禁止虚拟方法的类同名的类,并且该类包含一个虚拟方法,但没有名称与其他类的名称相同的其他方法,会发生什么情况?该类将创建什么全局符号?我的期望是,如果存在两个同名的类但没有任何共同点,链接器可能不会发出警告,但如果两个类都有一个虚函数表,链接器可能会注册冲突。它是否真的会注册冲突将取决于所使用的名称修改规则。
What would happen if you created a source module which contained a class with the same name as the one where virtual methods were forbidden, and that class contained a virtual method but had no other methods whose names shadowed those of the other class? What global symbols would that class create? My expectation would be that if two classes with the same name exist but don't have anything in common, the linker would probably not squawk, but if both classes have a vtable, the linker might register a conflict. Whether it actually would register a conflict would depend upon the name-mangling rules in use.
在源代码管理中添加一条规则,拒绝包含“虚拟”一词的签入,向高级开发人员发送电子邮件,并扣留违规方的工资。
Add a rule to your source control that rejects check-ins that contain the word 'virtual', sends an email to a senior developer, and docks the pay of the offending party.
好吧,我真的认为这没有意义强制执行,但你可以使用 boost 类型特征'
is_polymorphic
或std::is_polymorphic
从 C++11 开始。编辑:示例:
Well, I really think this doesn't make sense to enforce, but you could use boost type traits'
is_polymorphic
orstd::is_polymorphic
from C++11 onward.EDIT: Example: