[問題] move constructor

看板C_and_CPP作者 (一閃)時間5年前 (2018/10/15 05:06), 5年前編輯推噓1(102)
留言3則, 2人參與, 5年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 5.4 問題(Question): #include<iostream> class A { public: A() {} A(const A& x) { std::cout << "Copy constructor\n"; } A(A&& x) { std::cout << "Move constructor\n"; } }; A func(int n) { // no RVO A temp1, temp2; if (n>0) return temp1; else return temp2; } int main() { A a1 = static_cast<const A&>(func(1)); // Move constructor } 不知道為什麼輸出會是Move constuctor而不是Copy constructor 照理說static_cast<const A&>應該把func(1)轉成lvalue了才對 而且就算輸出是Move constuctor 也不能不定義Copy constructor 否則會編譯錯 感謝解答 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.30.51 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1539551177.A.F42.html

10/15 06:24, 5年前 , 1F
編譯器幫你選move constructor 你有沒有轉都沒有意義
10/15 06:24, 1F

10/15 06:26, 5年前 , 2F
你把rvalue reference的constructor刪掉
10/15 06:26, 2F
意思是因為轉型後是lvalue 還是得定義Copy constructor來維持函式重載的語法正確性 但編譯器實作上選擇Move constructor是另一回事? ※ 編輯: KaryuuIssen (140.112.30.51), 10/15/2018 11:39:08

10/16 09:53, 5年前 , 3F
轉型跟constructor無關
10/16 09:53, 3F
文章代碼(AID): #1Rmw_9z2 (C_and_CPP)