21

不清楚如果我在 C++0x 中删除一个虚方法会发生什么:

 virtual int derive_func() = delete;

这是否意味着这个类以及从它继承的所有东西都不能定义/实现该derive_func()方法?或者这是非法/编译错误?

4

2 回答 2

17

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. 意味着它非常没用(至少我读过它)唯一有效的用途是:

struct A{
     virtual void b() = delete;
};
struct B:A{
     virtual void b() = delete;
};

这是完全没用的,因为永远无法调用该函数。对于非虚函数,使用更合理

编辑要完全清楚这是唯一可能的关系,孩子可能无法实现,您可能不会删除未删除的继承虚拟。

于 2010-10-11T22:33:54.927 回答
5

flynt 是对的,但我想指出的是,在最终的 C++11 草案(N3337)中,相应的语言已移至第 10.3#16 节:

具有已删除定义的函数不应覆盖没有已删除定义的函数。同样,没有删除定义的函数不应覆盖具有删除定义的函数。2

对我来说(第 8.4.3#1 节)似乎相当清楚,删除的定义实际上算作定义,实际上是内联定义,这意味着删除的定义满足 10.3#11:

在类中声明的虚函数应在该类中定义或声明为纯函数,或两者兼而有之;但不需要诊断。2

However, it seems that current implementations disagree. Here's my test case:

struct Base {
    virtual void bar();
    virtual void foo() = delete;
};

void Base::bar() { }  // a definition of the first non-inline virtual function
int main() { Base b; }
  • Clang produces an unlinkable program: Base::foo is mentioned in the vtable for Base. And if you swap the order of foo and bar, the linker complains that the entire vtable is missing (because Clang thinks foo 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 identify bar as the first non-inline virtual member function, no matter the order of foo and bar.

于 2012-08-24T00:59:18.570 回答