首先看个程序。
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A"<<endl;
}
~A()
{
cout << "~A"<<endl;
}
private:
int x;
};
void main()
{
A a;
A b(a);
A c(a);
}
输出结果是:
A
~A
~A
~A
请按任意键继续. . .
=================================================
关于函数参数和函数返回值的构造问题。
函数参数和返回值的构造都是调用的拷贝构造函数。
并且在函数返回时都需要析构。
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A" <<endl;
}
~A()
{
cout << "~A" <<endl;
}
private:
string x,y;
};
class B : public A
{
public:
B()
{
cout << "B" <<endl;
}
~B()
{
cout << "~B" <<endl;
}
private:
string x1,y1;
};
B fun(B b)
{
return b;
}
void main()
{
B a,b;
b = fun(a);
}
输出结果:
A
B
A
B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .
当把函数调用注释掉后,输出结果是:
A
B
A
B
~B
~A
~B
~A
请按任意键继续. . .
可见相比fun函数的调用,只是多了两次析构函数的调用而已。
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A" <<endl;
}
A(const A &a)
{
cout << "construct A" <<endl;
}
~A()
{
cout << "~A" <<endl;
}
private:
string x,y;
};
class B : public A
{
public:
B()
{
cout << "B" <<endl;
}
B(const B &a)
{
cout << "construct B" <<endl;
}
~B()
{
cout << "~B" <<endl;
}
private:
string x1,y1;
};
B fun(B b)
{
return b;
}
void main()
{
B a,b;
b = fun(a);
}
PS:调用拷贝构造函数之前会自动调用父类的构造函数
A
B
A
B
A
construct B
A
construct B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .
//多余调用的两次析构函数。是函数参数和返回值的析构。
//而函数参数和返回值都是拷贝构造函数完成构造的。
//参考文献:
//http://www.cnblogs.com/renyuan/archive/2012/12/29/2839230.html