成员方法如何删除对象? [英] How could a member method delete the object?

查看:159
本文介绍了成员方法如何删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习COM,以下代码让我困惑。

I am currently studying COM and the following code confused me.

STDMETHODIMP _(ULONG) ComCar::Release()
{
  if(--m_refCount==0)
    delete this; // how could this "suicide" deletion be possible?
  return m_refCount;
}



我想知道如何可以删除其成员中的对象实例方法?所以我做了以下实验:

I am wondering how could it be possible to delete an object instance within its member method? So I made the following experiment:

class A
{
public:
    void Suicide(void);
    void Echo(void);
    char name;
};

void A::Echo(void)
{
    ::printf("echo = %c\n",name);
}

void A::Suicide(void)
{
    delete this;
}

int main(void)
{
    A a;
    a.name='a';
    a.Suicide(); //failed
}

并且执行在。调试报告一些调试失败。有人能给我一些光吗?因为我完全是COM的新手。

And the execution does failed at a.Suicide(). The debug report some "Debug Assertion Failed". Could someone shed some light on me? Cause I am totally a newbie on COM.

相关的主题在这里:关于COM Release()方法的问题

推荐答案

A* a = new A();
a->name='a';
a->Sucide();

您只能删除 new ,当然 - 如果删除在成员函数或其他地方没有区别。

You can only delete what was built by new, of course -- it makes no difference if that delete is in a member function or elsewhere.

这篇关于成员方法如何删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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