问题描述
我无法理解:
double * x = new double;
const double * p = x;
删除p;
有效。为什么我被允许删除一个const指针?同样的说明:
为什么我可以这样做:
class probna {
//
};
probna pr;
const probna& ref_pr = p;
ref_pr。〜probna();
拜托,赐教!
因为指针/对象/引用的常量无关。
模板< class T>
void f()
{
//确保T永远不会改变
const T * t = new T;
/ /呵呵..我该怎么做才能删除t?
}
Jonathan
不,除非使用智能指针或手柄。
如果绝对的话需要一个原始指针,你可以在类中定义一个运算符
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!
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
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指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!