为什么要使用“const T*”?简单地转换为“void*”在“操作员删除”中?
可能的重复:
删除指向 const (T const*) 的指针
void operator delete (void*);
...
const char *pn = new char, *pm = (char*)malloc(1);
delete pn; // allowed !!
free(pm); // error
演示。
可以理解的是,free()
是一个函数,因此 const void*
不能转换为 void*
。但是为什么在operator delete
(默认或重载)的情况下允许它呢?
它在功能上不是一个错误的构造吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不是。
delete
表达式首先调用析构函数。 之后销毁后,您将留下一个
void*
。 (典型的实现,事实上,析构函数调用了operator delete()函数,因为
调用哪个
operator delete()
取决于最底层的派生类。)至于为什么你的
T const*
在析构函数中变成了T*
: 这是任何不同于:
?人们可以争论不同的规则,但最终,析构函数是
特殊,并遵守特殊规则。
It's not. The
delete
expression first calls the destructor. Afterdestruction, you are left with a
void*
. (The typical implementation,in fact, has the destructor call the
operator delete()
function, sincewhich
operator delete()
to call depends on the most derived class.)As to why your
T const*
becomes aT*
in the destructor: is this anydifferent than:
? One can argue for different rules, but in the end, destructors are
special, and obey special rules.
虽然我非常同意@JamesKanze 的回答,但也许有人想看看该标准实际上说了些什么。根据标准(§12.1/4):
和(§12.4/2):
公平地说,这只不过是重申@James所说的,更具体一点:该对象仅在 ctor 完成时才真正被视为对象(或所有 ctor,当继承时)涉及)直到第一个 dtor 开始。在这些边界之外,不强制执行 const 和 volatile。
While I quite agree with @JamesKanze's answer, perhaps somebody would like to see what the standard actually says. According to the standard (§12.1/4):
and (§12.4/2):
In fairness, this does little more than re-state what @James said, a bit more specifically: the object is only really considered an object from the time the ctor finishes (or all the ctors, when inheritance is involved) to the point that the first dtor begins. Outside those boundaries, const and volatile aren't enforced.