为什么要删除const指针? [英] Why can you delete a const pointer?

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

问题描述

我无法理解:


double * x = new double;

const double * p = x;

删除p;


有效。为什么我被允许删除一个const指针?同样的说明:

为什么我可以这样做:


class probna {

//

};


probna pr;

const probna& ref_pr = p;


ref_pr。〜probna();


拜托,赐教!

解决方案

Roman Werpachowski写道:

我无法理解:

double * x = new double;
const double * p = x;
删除p;

有效。为什么我被允许删除一个const指针?同样的说明:
为什么我可以这样做:

类probna {
//
};

probna pr ;
const probna& ref_pr = p;

ref_pr。~proxna();




因为指针/对象/引用的常量无关<分配,删除,构造或销毁的



模板< class T>

void f()

{

//确保T永远不会改变

const T * t = new T;


/ /呵呵..我该怎么做才能删除t?

}

Jonathan


所以如果我决定通过引用/指针来访问它,就没有办法确保有人不删除我的成员

对象?


Roman Werpachowski写道:

所以没有办法确保有人不删除我的成员
对象,如果我决定通过它来访问它一个参考/指针?




不,除非使用智能指针或手柄。


如果绝对的话需要一个原始指针,你可以在类中定义一个运算符

delete()并将其设为私有。这将捕获删除

p;但是不可能直接创建对象(新T)。

请注意,使用全局

运算符可以挫败这些限制。


为什么首先将指针放在第一位?如果你提供参考,那么人们将会更愿意删除这个对象。


Jonathan


I can''t understand this:

double * x = new double;
const double * p = x;
delete p;

works. Why am I allowed to delete a const pointer? On the same note:
why am I allowed to do this:

class probna {
//
};

probna pr;
const probna& ref_pr = p;

ref_pr.~probna();

Please, enlighten me!

解决方案

Roman Werpachowski wrote:

I can''t understand this:

double * x = new double;
const double * p = x;
delete p;

works. Why am I allowed to delete a const pointer? On the same note:
why am I allowed to do this:

class probna {
//
};

probna pr;
const probna& ref_pr = p;

ref_pr.~probna();



Because the constness of a pointer/object/reference has nothing to do
with allocation, deletion, construction or destruction.

template <class T>
void f()
{
// make sure the T never changes
const T* t = new T;

// huh.. what do I do here to delete t?
}
Jonathan


So there is no way to make sure that someone does not delete my member
object, if I decide to give access to it via a reference/pointer?


Roman Werpachowski wrote:

So there is no way to make sure that someone does not delete my member
object, if I decide to give access to it via a reference/pointer?



No, except by using a smart pointer or a handle.

If you absolutely need a raw pointer, you could define an operator
delete() in the class and make it private. This would catch a "delete
p;" but would make it impossible to create objects directly (new T).
Note that both these restrictions could be foiled by using the global
operators.

Why give the pointer in the first place anyways? People will be much
less tempted to delete the object if you give a reference.

Jonathan


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

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