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

查看:223
本文介绍了删除指向const的指针(T const *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于const指针的基本问题。我不允许使用const指针调用任何非const成员函数。但是,我允许这样做一个const指针:

  delete p; 

这将调用类的析构函数,它本质上是一个非常量'方法'。为什么这是允许的?只是支持这个:

 删除这个; 

还是有其他原因?

解决方案

它支持:

  //动态创建不能更改的对象
const Foo * f = new Foo;

//这里使用const成员函数

//删除它
delete f;但是请注意,问题不限于动态创建的对象:


  {
const Foo f;
//使用它
} //析构函数在这里调用

不是在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;

Or is there some other reason?

解决方案

It's to support:

// 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

If destructors could not be called on const objects we could not use const objects at all.

这篇关于删除指向const的指针(T const *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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