schatter
schatter

Reputation: 11

C++: how does the destructor work internally and who calls the default destructor?

class A
{
    public:
    A()
    {
       std::cout << "I am ctor\n";
    }
    ~A()
    {
       std::cout << "I am dtor\n";
    }
    void printme()
    {
       std::cout << "I am printme\n";
    }
};

int main()
{
   A aobj;
   aobj.printme();
   aobj.~A();
   aobj.printme();
   return 0;
}

And this is the output:

$./testdtor
I am ctor
I am printme
I am dtor
I am printme
I am dtor

An explicit call to destructor behaves like a normal function call and once the object goes out of scope, the destructor is called, but I would like to know by which entity?

Upvotes: 1

Views: 496

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254451

It depends on where the object is, and what it's lifetime is.

  • For automatic variables like your example, by code generated at the end of its scope
  • For static variables, by code called by the atexit mechanism after main ends
  • For thread-local variables, by a similar mechanism after the thread ends
  • For non-static class member variables or base sub-objects, by code generated in the destructor of the class containing it
  • For objects created by new, by code generated by the corresponding delete-expression
  • For objects created by placement-new, the destructor can only be called explicitly.

Upvotes: 6

bobah
bobah

Reputation: 18864

Compiler generates destructor invocation code for all automatic objects. Such destructors are invoked in the order opposite to the object construction order.

The delete operator calls object destructor for the object residing at the address pointed to by the operator argument and is normally (I would say always) used with the dynamic objects.

This behavior allows reliable memory management and many other useful tricks we love so much in C++.

The only situation where you may and in most cases would call destructor manually is when allocating an object using placement new operator.

Upvotes: 6

Ivan Mushketyk
Ivan Mushketyk

Reputation: 8285

Internally destructor is a usual function. It is used to free resources used by a class and it can have any behaviour.

Calls to destructors are generated by compiler. It called when:

1 Object goes out of scope

void foo() {
    // Declare an instance of some object
    MyClass object;

    // code

    // destructor for 'object' called here
}

2 When you delete an object: delete myPtr

3 When you delete an array of objects: delete[] myArray

4 If exception is thrown destructors are called for all objects in the scope

There is a case when destructor will not be called. If and exception is thrown during execution object's constructor and escapes it without being catched, destructor for this this object will not be called.

Upvotes: 0

Related Questions