看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 問題(Question): 最近看到一個範例,想不懂為何這個x是個lvalue被forward兩次之後變成 rvalue ??我的理解x本來是lvalue,forward應該都還是lvalue阿!! #include <iostream> void PrintT(int& t) { std::cout << "lvalue" << std::endl; } template <typename T> void PrintT(T&& t) { std::cout << "rvalue" << std::endl; } template <typename T> void TestForward(T&& v) { PrintT(std::forward<T>(v)); } void Test() { int x = 1; TestForward(std::forward<int>(x)); } Output: rvalue -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.9.34.163 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1623579964.A.2DF.html
g0010726: 第一個錯誤是:應該寫成 06/13 19:03
g0010726: TestForward(std::forward<int&>(x)) 06/13 19:03
a27417332: 因為 Test 裡面在傳引數的時候就用 forward<int>(x) 06/13 19:04
a27417332: 可想下 TestForward 的引數是右值時,T 會被推導成甚麼 06/13 19:06
g0010726: 第二個是 void PrintT(T&& t) 其實不代表是rvalue, 06/13 19:08
g0010726: 而是接受任何一種變數 (當然如果是int&的話 06/13 19:09
g0010726: 一般function優先) , 可以搜尋universal reference了解 06/13 19:09
lovejomi: 一開始就不該用forward 你的用法 效果上會變成 std::mov 06/16 03:37
lovejomi: e(x) 轉型成rvalue了 才會走到universal reference的Pri 06/16 03:37
lovejomi: ntT 06/16 03:37