Can a destructor be recursive?

后端 未结 5 756
北荒
北荒 2021-02-01 00:55

Is this program well-defined, and if not, why exactly?

#include 
#include 
struct X {
    int cnt;
    X (int i) : cnt(i) {}
    ~X()          


        
5条回答
  •  余生分开走
    2021-02-01 01:39

    Why would anyone ever want to call the destructor recursively in this way ? Once you have called the destructor, it should destroy the object. If you call it again, you would be trying to initiate the destruction of an already partly destroyed object when you were still actually part way through actually destroying it at the same time.

    All of the examples have some sort of decremental / incremental end condition, to essentially count down in calls, which is suggestive of some sort of failed implementation of a nested classs which contains members of the same type as itself.

    For such a nested matryoshka class, calling the destructor on the members, recursively, ie the destructor calls the destructor on member A, which in turn calls the destructor on its own member A, which in turn calls the detructor ... and so on is perfectly fine and works exactly as one might expect. This is a recursive use of the destructor, but it is not recursively calling the destructor on itself which is insane, and would make almost no sense.

提交回复
热议问题