难以跟踪代码的输出

时间:2015-10-11 11:21:01

标签: c++ constructor destructor

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();
    t.~Test();
}
int main()
{
    Test();
    Test t;
    fun(t);
     return 0;
}

输出我得到的代码如下:

 **Constructor is executed**   //This is when Test() is called
 **Destructor is executed**    //This is when Test() is called
 **Constructor is executed**   //This is when Test t is called
 //In the fun function
 **Constructor is executed**   //This is when Test() is called
 **Destructor is executed**   //This is when Test() is called
 **Destructor is executed**   //This is when t.~Test() is called
 **Destructor is executed**   // Don't know where this destructor comes from!
 **Destructor is executed**   //This is when Test t is called

我无法追踪第二个“析构函数执行”所属的位置...... !!!

1 个答案:

答案 0 :(得分:0)

#include "stdafx.h"
#include <iostream>
#include <conio.h>

using std::cout;

class Test
{
public:
    Test() { cout << "Constructor is executed\n"; }  
    ~Test() { cout << "Destructor is executed\n"; }
    friend void fun(Test t);
};
void fun(Test t) // Construct new object can be displayed by adding Test(const Test& rhs) { cout << "Constructor is executed\n"; }
{
    Test();
    t.~Test(); // Destruct created object
} 

int main()
{
    Test();
    Test t;
    fun(t);
    _getch();
     return 0;
}