Automatic destruction of object even after calling destructor explicitly

后端 未结 5 1630
野趣味
野趣味 2021-01-23 09:05

The following program :

#include 
using namespace std;

class Test
{
public:
    Test() { cout << \"Constructor is executed\\n\"; }
    ~Te         


        
5条回答
  •  清酒与你
    2021-01-23 09:36

    You've introduced undefined behavior.

    Per the standard:

    § 12.4 Destructors

    (11) A destructor is invoked implicitly

    (11.3) — for a constructed object with automatic storage duration (3.7.3) when the block in which an object is created exits (6.7),

    and

    15 Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended (3.8). [ Example: if the destructor for an automatic object is explicitly invoked, and the block is subsequently left in a manner that would ordinarily invoke implicit destruction of the object, the behavior is undefined. —end example ]

    You explicitly call the destructor or by calling t.~Test(), it is then implicitly invoked when the object leaves scope. This is undefined.

    The standard provides this note as well:

    14 [ Note: explicit calls of destructors are rarely needed. One use of such calls is for objects placed at specific addresses using a placement new-expression. Such use of explicit placement and destruction of objects can be necessary to cope with dedicated hardware resources and for writing memory management facilities.

提交回复
热议问题