C++/Syntax

C++ 레퍼런스 (Reference, 참조)

Caniro 2021. 3. 12. 17:19

레퍼런스 (Reference, 참조)

함수의 인자로 const int & 형태를 자주 사용하는 이유

  • 레퍼런스 : 불필요한 복사가 발생하지 않아서 성능 상 이점을 가진다.

  • const : rvalue도 인자로 넘길 수 있어서 확장성이 좋아진다.


Call by Reference

  • 포인터를 레퍼런스로 전달하는 방법

    #include <iostream>
    
    void    foo(int*& ptr)
    {
        std::cout << ptr << ' ' << &ptr << std::endl;
    }
    
    int     main()
    {
        using namespace std;
    
        int        x = 5;
        int*    ptr = &x;
    
        cout << ptr << ' ' << &ptr << endl;
        foo(ptr);
    }