C++에서 &
을 이용하여 참조로 전달할 수 있다. 이렇게 되면 데이터를 복사하는 것이 아닌 해당 메모리에 있는 데이터를 그대로 사용하게 된다.
참조로 전달하는 것이 재미있는 것은 포인터가 하지 못하는 것을 할 수 있다는 것이다. 포인터를 통해서 주소를 전달하는 것도 데이터 복사를 하지 않는다. 왜냐하면 주소 자체를 전달하는 것이므로 함수에서는 주소를 접근하기 때문이다.
하지만, 함수 내에서 해당 주소를 변경하게 되면 기존 파라미터로 전달한 주소는 변경되지 않는다는 점이다.
기존에 한 주소에 두 개의 포인터가 연결되었는데, 그 중 한 포인터가 새로운 주소에 연결되었다고 이해하면 된다.
이렇기 때문에 참조가 필요하다. 주소를 전달해서 원본 주소도 변경하고 싶을 때에는 포인터를 참조로 전달
하면 되기 때문이다.
#include <iostream>
int v = 9;
int *b = &v;
// 주소 변경이 안됌. (포인터 주소의 값 변경은 가능)
// 디버깅을 돌려보면 값이 변경이 안되는 것을 볼 수 있는데,
// 이는 func0을 나가는 순간 변경했던 주소가 원래주소로 돌아오게되면서 초기화가 되기 떄문이다.
void func0(int* p) {
*p = 3;
p = b;
*p = *b;
}
// 주소 변경이 가능
void func1(int* &p) {
p = b;
}
int main() {
int value = 7;
int *a = &value;
func0(a);
std::cout << *a << " " << a << std::endl;
std::cout << *b << " " << b << std::endl;
func1(a);
std::cout << *a << " " << a << std::endl;
return 0;
}
'C++' 카테고리의 다른 글
cpp : pass by *(pointer)와 &(reference) (0) | 2024.07.17 |
---|---|
[C++] class와 virtual (0) | 2024.05.22 |