개념

  • std::ref는 객체를 참조로 감싸서 std::reference_wrapper<T> 객체로 만들어주는 함수
  • 참조를 값처럼 복사하면서도 참조 성질을 유지하게 해줌
  • C++11에서 도입

정의

  template<class T>
std::reference_wrapper<T> std::ref(T& t);
  
  • t는 참조로 전달되며, 반환된 reference_wrapper는 내부 참조를 유지함

사용 목적

  • std::bind, std::function, std::thread 등에 인자를 넘길 때 기본은 복사
  • 참조로 넘기고 싶을 경우 std::ref()로 감싸야 함

예제

  #include <iostream>
#include <functional>

void print(int& x) {
    x += 1;
    std::cout << x << '\n';
}

int main() {
    int a = 10;

    // auto f = std::bind(print, a);      // 값 복사 (참조 아님)
    auto f = std::bind(print, std::ref(a)); // 참조 유지

    f();             // a == 11
    std::cout << a;  // 출력: 11
}
  

std::cref

  • std::ref와 동일하지만 const 참조용 래퍼
  const int a = 42;
auto r = std::cref(a); // std::reference_wrapper<const int>
  

주요 사용처

  • std::bind
  • std::thread
  • std::function
  • 람다 캡처 시 간접 참조를 원할 경우