删除指向 const (T const*) 的指针 [英] Deleting a pointer to const (T const*)

查看:26
本文介绍了删除指向 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*) 的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆