보편참조(전달참조)

생성일
Sep 3, 2023 11:53 PM
태그
#include<iostream> using namespace std; //보편참조 universal refenrence //전달참조 forwarding reference //오른값 참조랑 비슷하게 생김 && -> 오른값 참조 class Knight { public: Knight() { cout << "기본 생성자" << endl; } Knight(const Knight&) { cout << "복사 생성자" << endl; } Knight(Knight&&) noexcept { cout << "이동 생성자" << endl; } }; void Test_RValueRef(Knight&& k) // 오른값 참조 { } template<typename T> void Test_ForwardingRef(T&& param) { } int main() { Knight k1; Test_RValueRef(static_cast<Knight&&>(k1)); // 오른값 참조로 형변환 // std::move 사용해도 됌 Test_ForwardingRef(std::move(k1)); Test_ForwardingRef(k1); // ?? 왼값 오른값 통과 됌. auto&& k2 = k1; //Knight&& 는 아닐까? 아님 마우스를 가져다 대면 }
 
notion image
notion image
분명 똑같은 ForwardingRef를 통해 오른값 참조를 받는 줄 알았지만.
std::move를 사용하면 오른값 참조를, 그냥 k1을 넣으면 왼값 참조를 받아들이는 모습을
볼 수 있다.
auto&& k2 = k1; Knight&& k3 = static_cast<Knight&&>(k1);
또 위와 같이 auto에 &&를 사용하면 오른값 참조를 받을 것 처럼 보이지만
notion image
그렇지 않음을 알 수 있다.
notion image
하지만 위와 같이 오른값 참조를 캐스팅 하거나 std::move를 사용하면 &&를 받는 모습을
볼 수 있다.
 

Auto 와 template에 의해

전달 참조가 발생함