Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could a member method delete the object?

Tags:

c++

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
}

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.

A related thread is here: Question about COM Release() method

like image 980
smwikipedia Avatar asked Feb 22 '10 06:02

smwikipedia


People also ask

Which method do we use to remove a property from an object?

The delete operator removes a property from an object. If the property's value is an object and there are no more references to the object, the object held by that property is eventually released automatically.

How do you delete object items?

Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.

How do you delete an object in Java?

The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given List.

How do you delete a class object?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


1 Answers

Change your main's body to:

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

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.

like image 158
Alex Martelli Avatar answered Sep 30 '22 18:09

Alex Martelli