Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly calling constructors and destructors in C++

Tags:

c++

c++11

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?

like image 885
Naveen Avatar asked Dec 17 '25 21:12

Naveen


1 Answers

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.

like image 149
Ivan Rubinson Avatar answered Dec 20 '25 13:12

Ivan Rubinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!