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*) 的指针


基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01