我正在尝试了解虚拟析构函数。以下是本页的复制粘贴When to use virtual destructors?
Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet:
Base *b = new Derived(); // use b delete b; // Here's the problem!
[...] If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and non-virtual; by doing so, the compiler won't let you call delete on a base class pointer.
我不明白为什么通过使用 protected 非虚拟基类析构函数来防止删除。编译器不认为我们正在尝试调用
delete
来自基类对象? protected
是什么意思有关系吗?
最佳答案
C++ 标准对 delete
有这样的说法。 (第 5.3.5p10 节):
Access and ambiguity control are done for both the deallocation function and the destructor (12.4, 12.5).
因此,只有有权访问析构函数的代码才能使用
delete
.因为析构函数是 protected
,这意味着没有人可以调用delete
在 Base*
类型的指针上.只有子类才能使用析构函数(唯一可以使用的是子类自己的析构函数,作为子对象销毁过程的一部分)。当然,子类应该有自己的析构函数
public
,允许您通过子类类型删除对象(假设这是正确的实际类型)。注意:实际上,
Base
的其他成员可以做delete (Base*)p;
因为他们有访问权限。但是 C++ 假定使用这种结构的人不会这样做——C++ 访问控制只为您的类之外的代码提供指导。
关于c++ - 基类中 protected 非虚拟析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579435/