mardi 5 juillet 2016

Explicitly calling constructors and destructors in C++

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?

Aucun commentaire:

Enregistrer un commentaire