Can a destructor be recursive?

后端 未结 5 799
北荒
北荒 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:53

    The answer is no, because of the definition of "lifetime" in §3.8/1:

    The lifetime of an object of type T ends when:

    — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or

    — the storage which the object occupies is reused or released.

    As soon as the destructor is called (the first time), the lifetime of the object has ended. Thus, if you call the destructor for the object from within the destructor, the behavior is undefined, per §12.4/6:

    the behavior is undefined if the destructor is invoked for an object whose lifetime has ended

提交回复
热议问题