我有一个关于 const 指针的基本问题。我不允许使用 const 指针调用任何非 const 成员函数。但是,我可以在 const 指针上执行此操作:
delete p;
这将调用本质上是一个非常量“方法”的类的析构函数。为什么允许这样做?是不是只是为了支持这个:
delete this;
还是有其他原因?
最佳答案
为了支持:
// dynamically create object that cannot be changed
const Foo * f = new Foo;
// use const member functions here
// delete it
delete f;
但请注意,问题不仅限于动态创建的对象:
{
const Foo f;
// use it
} // destructor called here
如果无法在 const 对象上调用析构函数,我们根本无法使用 const 对象。
关于c++ - 删除指向 const (T const*) 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/755196/