delete的用法,不是通过new的对象可以delete来销毁吗?为什么?谢谢

Justin_Song 2002-06-22 11:00:56
delete的用法,不是通过new的对象可以delete来销毁吗?为什么?谢谢
...全文
213 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
导工 2002-06-23
  • 打赏
  • 举报
回复
不知大家有没有试过
#include <iostream.h>
class a
{
public:
a()
{cout<<"construct"<<endl;}
~a()
{cout<<"destruct"<<endl;}
void f(void)
{cout<<"abc"<<endl;}
};

int _tmain(int argc, _TCHAR* argv[])
{
a *p;
p=new a();
p->f();
delete p;
return 0;
}

结果是:

construct
abc
destruct
zdhe 2002-06-23
  • 打赏
  • 举报
回复
by default, delete implemented differently from free.
also for malloc(relloc, calloc) with new.

of course, as c++ spec, if not simple type , new can run your constructor. delete will call desctructor.

anyway, any of them at last use same logic as HeapAlloc.
Lostinet 2002-06-23
  • 打赏
  • 举报
回复
我明白为什么desctructor要定义为虚拟的了。。。不然:

CBase
{
...
int ref=0;
CBase(){ref=1}
Release(){ref--;if(ref<=0)delete this};
~CBase(){...}
}
CChild:CBase
{
~CChild()
}
..
如果~CBase不是虚拟的,那么在CBase::Release里面调用delete this不是很容易就变成了调用 ~CBase 了?
是不?
zdhe 2002-06-23
  • 打赏
  • 举报
回复
of course not.

all func (include desctructor) has saved in C++ class vtable (not instance).

your pvoid does not hold any vtable, so never run.
Lostinet 2002-06-23
  • 打赏
  • 举报
回复
奇怪。。
MyClass *pmc=new MyClass();
LPVOID *pvoid=pmc;
delete pvoid;会不会执行 ~MyClass 呢??
bugz 2002-06-22
  • 打赏
  • 举报
回复
malloc的可以用delete的。因为默认的分配器是一样的,除非你重载了new
delete运算符
sdjnlf 2002-06-22
  • 打赏
  • 举报
回复
不是通过new的对象不能用delete来销毁.new和delete是运算子不是函数,delete 用来删除由new建立的对象,释放指针指向的内存空间.
codingcoding 2002-06-22
  • 打赏
  • 举报
回复
new 的对象必须通过free来销毁。语法规定是这么的。不为什么。那你想用什么来销毁呀

16,548

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • AIGC Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧