C++关于析构函数的问题

# include <iostream># include <string>using namespace std;class F{ int n; int d;public: F(int n = 0, int d = 1); F(const F& f); ~F();};F::F(int n, int d) : n(n), d(d){ cout << "F(" << n << ✀,✀ << d << ✀)✀ << endl;}F::F(const F& f) : n(f.n), d(f.d){ cout << "F(F)" << &f <<endl;}F::~F(){ cout << "~F(" << n << ✀,✀ << d << ✀)✀ << "::::" << this << endl;}F fun(F x){ return x;}int main(){ F a(1, 2); cout << "<<<<<<<<<<<<<<<<<<<<<<" << endl; fun(a); cout << "<<<<<<<<<<<<<<<<<<<<<<" << endl; return 0;}/*输出的结构如下F(1,2)<<<<<<<<<<<<<<<<<<<<<<F(F)0xbfccafc8 F(F)0xbfccafd8 ~F(1,2)::::0xbfccafd0 // 请问它是从哪里来的??~F(1,2)::::0xbfccafd8<<<<<<<<<<<<<<<<<<<<<<~F(1,2)::::0xbfccafc8*/
2026年09月17日 00:52
有2个网友回答
网友(1):

fun(a);调用的时候,先拷贝构造参数x,然后拷贝构造匿名的返回值。fun函数调用结束,参数x析构。然后返回值没有人使用,也进行析构,这就是中间那部分函数调用过程的输出。
你可以试试看
F b = fun(a); 这样的话返回值的析构会在return 0前才执行。
另外,你的拷贝构造函数输出的是参数f的指针,你改成这样会更加清楚:
F::F(const F& f) : n(f.n), d(f.d)
{
cout << "F(F)" << this <}

网友(2):

那就是析构函数啊 F()函数执行后执行的~F()