Should “delete this” be called from within a member method?

前端 未结 12 2026
醉酒成梦
醉酒成梦 2020-12-03 10:55

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

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

12条回答
  •  天涯浪人
    2020-12-03 11:21

    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;
      }
    }
    

提交回复
热议问题