删除指向 const (T const*) 的指针

2022-01-23 00:00:00 constants c++ delete-operator

我有一个关于 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.

相关文章