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

前端 未结 12 2025
醉酒成梦
醉酒成梦 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:00

    Getting ready for the down votes.

    Should it: No.
    Can it Technically: Yes
    Is it a good idea: Absolutely not.
    Are there situation it is useful: Of course. If you are C++ foo is exceedingly strong. But most people are not that good. So only do this if you have a team of people working with you able to do decent code review.

    Why:
    There is no way for an object to know that it has been dynamically allocated (and thus needs deleting) or is a normal object (and thus must not be deleted) and thus how can it decidide weather it should be deleted. Thus if an object is deleting itself then in my opinion there is somthing terribly wrong with the design.

    If you have an object that needs managing then you should write a seprate object to do the management (hence smart pointers). Let the object do what it is good at, then seporate the management of the object into another object.

提交回复
热议问题