c++ 析构函数的调用

来源:百度知道 编辑:UC知道 时间:2024/06/20 14:00:07
#include <iostream>
using namespace std;

class three_d
{
int x, y, z;
public:
three_d()
{
x = y = z = 0;
}
~three_d()
{
cout <<"destructor---\n ";
}
three_d(int i, int j, int k)
{
x = i;y = j;z = k;
}
three_d operator = (three_d op2);
void show();
};

three_d three_d::operator = (three_d op2)
{
x = op2.x;
y = op2.y;
z = op2.z;

return * this;
}

void three_d::show()
{
cout << x << ", ";
cout << y << ", ";
cout << z << "\n ";
}

int main()
{
three_d a(1, 2, 3), c;

cout << "before c = a;\n ";
c = a;
cout << " after c = a;\n ";
c.show();

return 0;
}

运行结果如下:

执行c = a时
1首先传递参数op2,他在复制构造函数结束时析构
2在复制构造函数结束时返回*this,即返回时制造了一个*this的副本(因为返回值是three_d而不是three_d&),这个副本在完成赋值后,即析构,故又产生了一个destructor--。
呵呵。

op2是值传递的形参,是进入函数前临时由拷贝构造函数生成的,函数结束后析构,这是一次.

另外return * this; 这里实际上也调用了拷贝构造函数,以*this为源生成了一个临时对象,返回了这个临时对象的值后,这个临时对象也析构了.

所以说,要多使用引用传递,返回类型前面也要用引用,这样就不用调用拷贝构造函数了