I know that one should not call destructors explicitly for local members as it results in undefined behaviour. But still I want to understand the output for following piece of code :
#include <iostream>
using namespace std;
class Test
{
public:
Test() { cout << "Constructor is executed\n"; }
~Test() { cout << "Destructor is executed\n"; }
friend void fun(Test t);
};
void fun(Test t)
{
Test(); //3.calls constructor and destructor
t.~Test(); //4. calls destructor
}
int main()
{
Test(); // 1. calls constructor and destructor
Test t; // 2.calls constructor
fun(t);
return 0; //5. compiler calls destructor for t
}
Expected output (3 destructor calls at the end):
Constructor is executed
Destructor is executed
Constructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
Destructor is executed
Actual output (4 destructor calls at the end):
Constructor is executed
Destructor is executed
Constructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
Destructor is executed
Destructor is executed
Where is th extra destructor call coming at the end?
You pass t to fun by value. It creates a copy.
The reason you don't see that is because you didn't make the copy constructor print anything.
But you do see it destructed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With