Reputation: 11
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
Reputation: 254451
It depends on where the object is, and what it's lifetime is.
atexit
mechanism after main
endsnew
, by code generated by the corresponding delete-expressionUpvotes: 6
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
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