class Test{
int x,y;
Test():x(0),y(0){}
Test(int a,int b):x(a),y(b){}
Test (const Test& t):x(t.x) y(t.y){} // #1
// explicit Test (const Test& t):x(t.x) y(t.y){} // #2
}
int main(){
Test t1;
Test t2(1,2);
Test t3(t2); // Test(Test)
// 이 경우 #1을 작성해주지 않으면 default copy constructor가 호출된다.
// default copy constructor의 형태는 #1과 같다
Test t4{t1};
Test t5= {t1};
Test t6=t1; // 이 경우 #2 explicit 함수의 경우 호출이 불가능하다.
// 위 3개 모두 default copy constructor를 호출하게 된다.
}
default copy constructor 를 구현하면서 확인해 볼 수 있는 것이 함수에서 call by value로 호출한다면 (== 리턴용 임시 객체가 생성될 때) 복사 생성자를 호출하는 것을 알 수 있다.
class Test{
int x,y;
Test():x(0),y(0){}
Test(int a,int b):x(a),y(b){}
Test (const Test& t):x(t.x) y(t.y){
print("Copy Constructor")
} // #1
}
void tmp(Test t){
}
void tmpConst(const Test& t){
}
Test g_t;
Test tmp2(){
return g_t;
}
Test& tmp2Const(){
return g_t;
}
int main(){
Test t1(1,2);
tmp(t1); // 이 경우 print("Copy Constructor")가 호출된다.
tmpConst(t1); // 이 경우 print("Copy Constructor")가 호출되지 않는다.
tmp2(); // print("Copy Constructor")가 호출됨
tmp2Const();
// print("Copy Constructor")가 호출되지 않음. 참조로 반환하면 return 용 임시 객체가 생성되지 않음
}