Is delete this allowed?

后端 未结 10 1377
-上瘾入骨i
-上瘾入骨i 2020-11-22 03:40

Is it allowed to delete this; if the delete-statement is the last statement that will be executed on that instance of the class? Of course I\'m sure that the ob

10条回答
  •  抹茶落季
    2020-11-22 04:03

    This is the core idiom for reference-counted objects.

    Reference-counting is a strong form of deterministic garbage collection- it ensures objects manage their OWN lifetime instead of relying on 'smart' pointers, etc. to do it for them. The underlying object is only ever accessed via "Reference" smart pointers, designed so that the pointers increment and decrement a member integer (the reference count) in the actual object.

    When the last reference drops off the stack or is deleted, the reference count will go to zero. Your object's default behavior will then be a call to "delete this" to garbage collect- the libraries I write provide a protected virtual "CountIsZero" call in the base class so that you can override this behavior for things like caching.

    The key to making this safe is not allowing users access to the CONSTRUCTOR of the object in question (make it protected), but instead making them call some static member- the FACTORY- like "static Reference CreateT(...)". That way you KNOW for sure that they're always built with ordinary "new" and that no raw pointer is ever available, so "delete this" won't ever blow up.

提交回复
热议问题