[C/C++] 레퍼런스(참조자) vs. 포인터 (Reference vs. Pointer)

전문가를 위한 C++(출처1) 책을 읽다가 Reference(레퍼런스, 참조) 변수에 대해서 알게 되어서 정리하였다. 개인적인 느낌이지만 Reference 변수를 잘 사용하면 Pointer를 사용할 때 보다 실수를 적게 하면서 프로그램을 작성할 수 있을 것 같다.

Pointer와 Reference 변수를 선언해서 사용하는 방법은 아래와 같다.

//MK: Pointer Syntax
Type *pointer;
pointer = variable name;
FunctionA(pointer);

void FunctionA(Type *pointer){
    //MK: pointer 값 변경 가능
    pointer = variable name;
}

//MK: Reference Syntax
Type& reference;
reference = variable name;
FunctionB(reference)

void FunctionB(Type& reference){
    //MK: Reference 값 변경 가능
    reference = variable name;
}

//MK: Const Reference Syntax
string& name = "hello"
FunctionC(name);

void FunctionC(const string& name){
    //MK: name string 변수는 const로 변경 불가능
    //MK: string을 복사하지 않기 때문에 효율적인 방법임
}

기본적으로 함수를 호출하면 변수를 복사해서 사용한다. 하지만 Pointer와 Reference를 사용하면 변수를 복사하지 않고 참조 전달 방식(Pass by reference)을 사용할 수 있다.

Pointer와 Reference는 거의 동일해 보이지만 아래와 같이 5개의 차이가 있다고 한다. 영어를 적확히 이해하지 못해서 그대로 복사하였다 (출처 2).

  1. References are used to refer an existing variable in another name whereas pointers are used to store address of variable.
  2. References cannot have a null value assigned but pointer can.
  3. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference.
  4. A reference must be initialized on declaration while it is not necessary in case of pointer.
  5. A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack.

지금까지 읽은 자료에서 느끼는 가장 큰 차이는 Reference 변수는 Null 값을 가질 수 없다. 그래서 Reference 변수는 생성과 동시에 초기화를 해줘야 한다. 그렇지 않으면 에러가 발생한다.


출처

  1. 전문가를 위한 C++
  2. https://www.tutorialspoint.com/pointers-vs-references-in-cplusplus#:~:text=References%20are%20used%20to%20refer,referenced%20but%20pass%20by%20reference.
  3. https://gracefulprograming.tistory.com/11#:~:text=%ED%8F%AC%EC%9D%B8%ED%84%B0%EB%8A%94%20%ED%95%A0%EB%8B%B9%20%ED%95%A0%20%EB%95%8C,%EB%8C%80%EC%83%81%EC%9D%84%20%EA%B7%B8%EB%8C%80%EB%A1%9C%20%ED%95%A0%EB%8B%B9%ED%95%A9%EB%8B%88%EB%8B%A4.&text=%EB%98%90%ED%95%9C%20%EB%A0%88%ED%8D%BC%EB%9F%B0%EC%8A%A4%EB%8A%94%20%EC%84%A0%EC%96%B8%EA%B3%BC,%EC%8B%9C%EC%97%90%EB%8F%84%20%EA%B0%99%EC%9D%B4%20%EC%A0%81%EC%9A%A9%EB%90%A9%EB%8B%88%EB%8B%A4.

Leave a Comment