Deleting a pointer to const (T const*)(删除指向 const (T const*) 的指针)
问题描述
我有一个关于 const 指针的基本问题.我不允许使用 const 指针调用任何非 const 成员函数.但是,我可以在 const 指针上执行此操作:
I have a basic question regarding the const pointers. I am not allowed to call any non-const member functions using a const pointer. However, I am allowed to do this on a const pointer:
delete p;
这将调用本质上是一个非常量方法"的类的析构函数.为什么允许这样做?是不是只是为了支持这个:
This will call the destructor of the class which in essence is a non-const 'method'. Why is this allowed? Is it just to support this:
delete this;
还是有其他原因?
推荐答案
为了支持:
// dynamically create object that cannot be changed
const Foo * f = new Foo;
// use const member functions here
// delete it
delete f;
但请注意,问题不仅限于动态创建的对象:
But note that the problem is not limited to dynamically created objects:
{
const Foo f;
// use it
} // destructor called here
如果无法在 const 对象上调用析构函数,我们根本无法使用 const 对象.
If destructors could not be called on const objects we could not use const objects at all.
这篇关于删除指向 const (T const*) 的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:删除指向 const (T const*) 的指针


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01