C++中的纯虚析构函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/630950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pure virtual destructor in C++
提问by Ivan Krechetov
Is it wrong to write:
是不是写错了:
class A {
public:
virtual ~A() = 0;
};
for an abstract base class?
对于抽象基类?
At least that compiles in MSVC... Will it crash at run time?
至少在 MSVC 中编译...它会在运行时崩溃吗?
回答by MSN
Yes. You also need to implement the destructor:
是的。您还需要实现析构函数:
class A {
public:
virtual ~A() = 0;
};
inline A::~A() { }
should suffice.
应该足够了。
And since this got a down vote, I should clarify: If you derive anything from A and then try to delete or destroy it, A
's destructor will eventually be called. Since it is pure and doesn't have an implementation, undefined behavior will ensue. On one popular platform, that will invoke the purecall handler and crash.
由于这得到了否决票,我应该澄清:如果您从 A 派生任何内容,然后尝试删除或销毁它,A
最终将调用 's destructor 。由于它是纯的并且没有实现,因此会出现未定义的行为。在一个流行的平台上,这将调用 purecall 处理程序并崩溃。
Edit: fixing the declaration to be more conformant, compiled with http://www.comeaucomputing.com/tryitout/
编辑:修复声明以使其更加符合,编译为http://www.comeaucomputing.com/tryitout/
回答by dirkgently
Private destructors: they will give you an error when you create an object of a derived class -- not otherwise. A diagnostic may appear though.
私有析构函数:当您创建派生类的对象时,它们会给您一个错误——否则不会。但可能会出现诊断信息。
12.4 Destructors
6 A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined.
12.4 析构函数
6 析构函数可以声明为虚(10.3)或纯虚(10.4);如果在程序中创建了该类或任何派生类的任何对象,则应定义析构函数。
A class with a pure virtual destructor is an abstract class. Note well:
具有纯虚析构函数的类是抽象类。请注意:
10.4 Abstract classes
2 A pure virtual function need be defined only if called with, or as if with (12.4), the qualified-id syntax (5.1).
[Note:a function declaration cannot provide both a pure-specifier and a definition —end note ]
10.4 抽象类
2 纯虚函数仅在使用或如同使用 (12.4) 限定 id 语法 (5.1) 调用时才需要定义。
[注意:函数声明不能同时提供纯说明符和定义——尾注]
Taken straight from the draft:
直接从草案中提取:
struct C {
virtual void f() = 0 { }; // ill-formed
};