#include<iostream>
using namespace std;
class Nick{
public:
Nick() {
cout << "Nick()..." << endl;
}
Nick(double c) {
cout << "Nick(double c)..." << endl;
}
Nick(const Nick& nick) {
m_id = nick.m_id;
cout << "Nick(const Nick& nick)..." << endl;
}
~Nick() {
cout << "~Nick()..." << endl;
}
int m_id;
};
1 用已经创建好的对象来初始化新的对象
void test01() {
Nick n1;
n1.m_id = 37;
Nick n2(n1);
}
2 以值传递的方式给函数参数传值
void doWork(Nick n1) { //Nick n1 = Nick(n)
}
void test02() {
Nick n;
n.m_id = 37;
doWork(n);
}
引用传递不会调用拷贝构造函数
void doWork(Nick &n1) { //Nick n1 = Nick(n)
}
void test02() {
Nick n;
n.m_id = 37;
doWork(n);
}
3 以值方式返回局部对象
Nick doWork2() {
Nick n1;
return n1;
}
void test03() {
Nick n = doWork2();
}
Debug模式下
Release模式下
Release下优化成什么样?
Nick n; //不调用默认构造
doWork2(p);
void doWork2(Nick &n){
Nick n1; //调用默认构造
}