nakka soft world !

복사 생성자 (Copy Constructor) 본문

프로그래밍언어/C++

복사 생성자 (Copy Constructor)

nakka 2017. 3. 17. 09:59
728x90

복사 생성자 (Copy Constructor)


1. 기본

class Point

{

public:

int x, y;

Point() : x(0), y(0) {}

Point(int a, int b) : x(a), y(b) {}


// 컴파일러가 생성해주는 복사 생성자. 사용자가 만들어도 무방함.

Point(const Point& p)

{

x = p.x;

y = p.y;

}

};

int main()

{

Point p1;  // OK

Point p2(1, 2); // OK

Point p3(1);  // Error

Point p4(p2); // Point(Point). 사용자가 만들지 않았지만 Compiler가 만들어줌. 자기 자신을 파라메터로 하는 생성자


cout << p4.x < endl;  // 1

cout << p4.y < endl;  // 2

}


2. 복사 생성자가 사용되는 경우

복사 생성자가 호출 되는 3가지 경우


class Point

{

private:

int x, y;

public:

Point() { cout << "Point()" << endl; }

~Point() { cout << "~Point()" << endl; }


Point(const Point& p)

{

cout << "Point(const Point& p)" << endl;

}

};


// 1. 객체가 동일한 타입의 객체로 초기화 될때

int main()

{

Point p1;

Point p2(p1);


Point p2 = p1;   // == Point p2(p1);


int a(0);

int a = 0;

}


// 2. 함수가 인자로 값을 받을 떄 (cal by value)

void foo(Point p2) // Point p2 = p1

{

}

-> 메모리도 잡히고, 복사생성자도 불리고, 소멸자도 불리기에 성능이 안좋음.

 Call by vlaue보다는 const사용. 아래와 같이 개선

void foo(const Point& p2)

{

}



int main()

{

Point p1;

foo(p1);

}



// 3. 함수가 객체를 값으로 리턴할때

Point p;


Point foo()

{

return p;  // 값을 리턴, 리턴용 임시 객체 생성. -> 이 위치에서 복사 생성자 만들어짐.

}

int main()

{

foo();

}


개선 방향

Point& foo() // 참조로 변경, 리턴용 임시 객체를 만들지 않음.

{

return p; // 참조 리턴

}

주의 사항. 지역변수는 참조 리턴 하면안됨. 전역변수만 가능.




3. RVO (Return Value Optimization)


Point foo()

{

Point p1;

return p1;  // 생성자 2회 , 소멸자 2회 호출됨


return Point(); // 임시 객체를 만드는 표현. 클래스 명에 괄호 치면 임시 객체

// 리턴용 임시 객체.

// 생성자 1회, 소멸자 1회 호출됨

}

int main()

{

foo();

}


728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

정적 멤버 데이터 (static member data)  (0) 2017.03.17
Object Copy  (0) 2017.03.17
initialize list, 초기화 리스트  (0) 2017.03.17
소멸자  (0) 2017.03.16
default function, delete function  (0) 2017.03.16
Comments