6.2 An example

Here is an example that illustrates when destructors are invoked:

#include <iostream>
using namespace std;
class X
{
  public:
    ~X(void);
};

X::~X(void)
{
  cout << "an X is getting destroyed" << endl;
}

int main(void)
{
  {
    cout << "entering a block" << endl;
    X x;
    cout << "exiting a block" << endl;
  }
}

When this program executes, it confirms that x is destroyed after the message ``exiting a block''. This is because an auto variable is destroyed upon the exit of a block, after the last statement (in the block).



Copyright © 2006-09-26 by Tak Auyeung