删除 C++0x 中的虚拟函数
目前尚不清楚如果我删除 C++0x 中的虚拟方法会发生什么:
virtual int derive_func() = delete;
这是否意味着该类以及从它继承的所有内容都无法定义/实现 derive_func() 方法?或者这是非法/编译错误?
It isn't clear what happens if I delete a virtual method in C++0x:
virtual int derive_func() = delete;
Does this mean this class and everything that inherits from it can not define/implement the derive_func()
method? Or is this illegal/compile error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://www.open-std .org/jtc1/sc22/wg21/docs/papers/2007/n2326.html#delete
删除的虚拟函数不能覆盖未删除的虚拟函数,反之亦然。
这意味着它非常无用(至少正如我读到的那样)唯一有效的用途是:
这是完全无用的,因为该函数永远无法被调用。对于非虚函数,使用更合理
编辑
需要完全明确的是,这是唯一可能的关系,子级可能不会实现,并且您可能无法删除未删除的继承虚拟。
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2326.html#delete
A deleted virtual function may not override a non-deleted virtual function and vice-versa.
meaning its pretty useless (as i read it at least) the only valid use would be:
which is completely useless, since the function can never be called. for non virtual functions the use is more justified
EDIT
to be completely clear this is the ONLY possible relation, children may not implement and you may not delete a non-deleted inherited virtual.
flownt 说得对,但我想指出的是,在最终的 C++11 草案(N3337)中,相应的语言已移至第 10.3#16 节:
对我来说(第 8.4.3#1 节)似乎相当清楚,删除的定义实际上可以算作定义,实际上是一个内联定义,这意味着删除的定义满足 10.3#11:
然而,当前的实现似乎不一致。这是我的测试用例:
Clang 生成一个不可链接的程序:
Base::foo
在Base
的 vtable 中提到。如果你交换foo
和bar
的顺序,链接器会抱怨整个 vtable 丢失了(因为 Clang 认为foo
是一个非-没有定义的内联函数)。 我将此作为错误提交;我们将看看开发人员的想法。GCC 抱怨在创建 vtable 时在翻译单元末尾“使用”了
foo
;但它确实正确地将bar
识别为第一个非内联虚拟成员函数,无论foo
和bar
的顺序如何。flownt got it right, but I want to point out that in the final C++11 draft (N3337), the corresponding language has moved to section 10.3#16:
It seems fairly clear to me (section 8.4.3#1) that a deleted definition does in fact count as a definition, and in fact an inline definition, which means a deleted definition satisfies 10.3#11:
However, it seems that current implementations disagree. Here's my test case:
Clang produces an unlinkable program:
Base::foo
is mentioned in the vtable forBase
. And if you swap the order offoo
andbar
, the linker complains that the entire vtable is missing (because Clang thinksfoo
is a non-inline function with no definition). I filed this as a bug; we'll see what the developers think.GCC complains about a "use" of
foo
at the end of the translation unit, when it creates the vtable; but it does correctly identifybar
as the first non-inline virtual member function, no matter the order offoo
andbar
.