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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With