例子:
#include <iostream>
#include <vector>
using namespace std;
struct X
{
X(){cout << "construct func X()" << endl;}
X(const X&){cout << "construct func X(const X&)" << endl;}
X& operator= (const X &rhs){cout << "copy assignment operator = (const X&)" << endl; return *this; }
~X(){cout << "deconstructor ~X()" << endl;}
};
void f1(X x)
{}
void f2(X &x)
{}
int main()
{
cout << "local: " << endl;
X x;
cout << endl;
cout << "Non reference parameter passing" << endl;
f1(x);
cout << endl;
cout << "Reference parameter passing" << endl;
f2(x);
cout << endl;
cout << "Dynamic allocation" << endl;
X *px = new X;
cout << endl;
cout << "Add to container" << endl;
vector<X> vx;
vx.push_back(x);
cout << endl;
cout << "Free dynamic allocation object" << endl;
delete px;
cout << endl;
cout << "Indirect initialization assignment" << endl;
X y = x;
y = x;
cout << endl;
cout << "Program over" << endl;
}
分析:
local:
construct func X()
Non reference parameter passing
construct func X(const X&)//非引用参数传递,拷贝构造函数
deconstructor ~X()//函数结束,调用析构函数
Reference parameter passing
//引用构造函数:传引用,不会调用构造和析构函数
Dynamic allocation
construct func X()//动态分配会调用构造函数
Add to container
construct func X(const X&)//将对象添加到容器中,会调用构造函数
Free dynamic allocation object
deconstructor ~X()//释放动态对象,会调用析构函数
Indirect initialization assignment
construct func X(const X&)//间接初始化,会调用拷贝构造函数
copy assignment operator = (const X&)//间接赋值,会调用赋值构造函数
Program over
deconstructor ~X()
deconstructor ~X()
deconstructor ~X()
// x y vx