Should “delete this” be called from within a membe

2019-01-11 22:34发布

I was just reading this article and wanted SO folks advice:

Q: Should delete this; be called from within a member method?

12条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-11 23:13

This was often used in the MFC days. IIRC the last message a window receives is WM_NCDESTROY, at which point you could call delete this, assuming you were some form of sadist of course (although MFC itself did this at times I think.)

查看更多
戒情不戒烟
3楼-- · 2019-01-11 23:13
  1. delete this can not be called from a non member function :)
  2. It is a bad idea to do until you understand it's consequences.
查看更多
Emotional °昔
4楼-- · 2019-01-11 23:15

Yes, there are a few cases where it is common.

Reference counting:

void release() 
{
  cnt--;
  if (cnt == 0) 
    delete this;
}

GUI programming. In some frameworks, when a user closes a window it is common for the window to delete itself.

查看更多
We Are One
5楼-- · 2019-01-11 23:18

Normally this is a bad idea, but it's occasionally useful.

It's perfectly safe as long as you don't use any member variables after you delete, and as long as clients calling this method understand it may delete the object.

A good example of when this is useful is if your class employs reference counting:

void Ref() {
  m_References++;
}

void Deref() {
  m_References--;
  if (m_References == 0) {
    delete this;
  }
}
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-11 23:22

Although not directly related to this thread i wanted to clarify this. I was asked a question that given a situation:

int* a = new int ;
int* b = a ;
delete a;

Now is the next statement safe?

cout<<*b ;

My answer: After delete a, the location pointed to by a has been marked for deletion and at any point of time it can be assigned to some other object. Hence accessing the value using b is not safe as it may get modified after being allocated to some other object.

Note: No downvoting please, this is just a clarification

查看更多
我只想做你的唯一
7楼-- · 2019-01-11 23:27

Yes you can and here's a good explanation of when and why

查看更多
登录 后发表回答