c++ - 基类中 protected 非虚拟析构函数

标签 c++ protected virtual-destructor

我正在尝试了解虚拟析构函数。以下是本页的复制粘贴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 ,这意味着没有人可以调用deleteBase* 类型的指针上.只有子类才能使用析构函数(唯一可以使用的是子类自己的析构函数,作为子对象销毁过程的一部分)。

当然,子类应该有自己的析构函数public ,允许您通过子类类型删除对象(假设这是正确的实际类型)。

注意:实际上,Base 的其他成员可以做delete (Base*)p;因为他们有访问权限。但是 C++ 假定使用这种结构的人不会这样做——C++ 访问控制只为您的类之外的代码提供指导。

关于c++ - 基类中 protected 非虚拟析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579435/

相关文章:

c# - protected 内部

android - 无法在 android (Android studio) 中测试 protected 方法

c++ - 编译器在 GCC 和 MSVC 中生成析构函数和警告

c++ - 将析构函数声明为 virtual 就足够了吗?

c++ - 不用于删除对象的基类的析构函数应该是虚拟的吗?

c++ - 如何为数组分配大量内存?

c++ - std::vector::push_back 不可复制对象给出编译器错误

c++ - 使用 protected 或公共(public)的虚拟函数?

c++ - 在 Windows 上使用 CMake 2.8.11 构建自定义 Qt 4.8.3 库时出错

python - 使用 C++ 或 Python 将表格 PDF 数据转换为文本(或任何其他可读格式)文件