int func() {return 5;}
int main() {
int a = func();
}
class A {
int x;
public:
A(int c) : x(c) {}
int& access_x() { return x; } // x의 참조(x 자체)를 리턴
int get_x() { return x; } // x의 값을 리턴
void show_x() { std::cout << x << std::endl; }
};
int main() {
A a(5);
a.show_x(); // 5
int& c = a.access_x(); // c는 x의 또다른 별명
c = 4; // x의 값이 4로 변경됨
a.show_x(); // 4
int d = a.access_x(); // x의 값을 복사
d = 3; // x에는 영향 없음
a.show_x(); // 4
}
int& c = a.access_x();
→ c는 int&이므로 x와 완전히 동일한 메모리 공간을 가리킴
→ c의 값을 바꾸면 a의 x도 바뀜
int d = a.access_x();
→ d는 int이므로 그냥 x의 값을 복사함
→ d를 바꿔도 x에 영향 없음
int &e = a.get_x(); // int& e = 4 에러
a.access_x() = 3; // a.x = 3과 동일
a.access_x()++; // a.x++과 동일
*this)를 반환하면 연속 호출 가능 class A {
int x;
public:
A(int c) : x(c) {}
A& decrease() { // 참조 리턴 함수
x--;
return *this; // 자신의 참조를 반환
}
void show_x() { std::cout << x << std::endl; }
};
int main() {
A a(10); // x = 10
a.decrease().decrease(); // 연속 호출
a.show_x(); // 8출력
}
a.decrease()의 결과 a.x의 값이 감소하고 객체 a가 반환됨a가 반환되었으므로 연속으로 decrease() 실행가능 class A {
int x;
public:
A(int c) : x(c) {}
A decrease() { // 참조 리턴 아닐 경우
x--;
return *this; // 자신의 참조를 반환
}
void show_x() { std::cout << x << std::endl; }
~A() {std::cout << "소멸자" << std::endl;}
};
int main() {
A a(10); // x = 10
a.decrease().decrease(); // 연속 호출이지만
a.show_x(); // 9출력
}
a의 메모리 주소가 decrease()로 들어가 함수 실행a.decrease()의 결과 a.x의 값이 감소하는 것까지는 동일main에서 새로운 메모리(임시 객체)를 생성, 반환 객체를 복사 (x=9). 이 메모리는 기존 a와는 개별적인 임시 객체임decrease() 실행x가 감소, a는 그냥 유지main에서 임시 객체를 생성하고 반환 객체를 복사a.decrease().decrease()가 끝나면 다시 임시 객체 2개는 소멸자 호출되며 소멸됨