[問題] unique_ptr與move

看板C_and_CPP作者 (好人超)時間7年前 (2016/08/10 23:25), 7年前編輯推噓10(10016)
留言26則, 5人參與, 最新討論串1/1
問題(Question): https://www.chromium.org/rvalue-references 在上面這個網頁裡,看到這段敘述 However, if the types of the variable and the return type do not match exactly, then you will have to use std::move() in order to convert without creating an extra temporary. std::unique_ptr<MyType> MakeMyType() { std::unique_ptr<ChildClassOfMyType> ptr; // This call to std::move() is needed to convert from a pointer-to-the // child class to a pointer-to-the parent. return std::move(ptr); } 我看不懂的是…為什麼這樣寫可以減少extra temporary呢? 如果不這麼寫的話又會造成什麼問題? (想知道這個寫法的反例?) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.25.206 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1470842731.A.732.html

08/10 23:40, , 1F
因為不這麼做,不能通過compile?
08/10 23:40, 1F

08/10 23:40, , 2F
可是我在MSVC跟GCC上,又都能通過compile...
08/10 23:40, 2F

08/10 23:43, , 3F
對於要convert type的unique_ptr,unique_ptr的
08/10 23:43, 3F

08/10 23:43, , 4F
constructor只接受r value。所以應該是這原因導致要move
08/10 23:43, 4F

08/10 23:45, , 5F
可能是return value都會當作r value,然後能用RVO的就用
08/10 23:45, 5F

08/10 23:46, , 6F
所以就剛好可以通過編譯了吧。以上是我的猜測,請求支援
08/10 23:46, 6F

08/11 00:54, , 7F
#19gioP8j Page9~12 , 講八個 string 相加的問題
08/11 00:54, 7F
靠這篇我有推結果自己完全沒消化 Q_Q

08/11 01:02, , 8F
不推別人會以為看不懂啊! @@
08/11 01:02, 8F

08/11 03:47, , 9F
你這樣問好像有點誤導 點進去才知道unique Ptt 是個例
08/11 03:47, 9F

08/11 03:47, , 10F
08/11 03:47, 10F

08/11 03:51, , 11F
簡單來說 return 一個不match 像是要int 你return long
08/11 03:51, 11F

08/11 03:51, , 12F
有可能有copy 發生
08/11 03:51, 12F

08/11 03:51, , 13F
使用move 可以確保不會有copy 因爲compiler 讀到知道
08/11 03:51, 13F

08/11 03:51, , 14F
不能copy
08/11 03:51, 14F

08/11 03:52, , 15F
要是我想的沒有錯的話 這個應該是建議而非require
08/11 03:52, 15F

08/11 03:53, , 16F
這裡提到這個的原因是因為簡單的情況下compiler 可以
08/11 03:53, 16F

08/11 03:53, , 17F
自己採用move semantics 但複雜的情況 要cast的情況可
08/11 03:53, 17F

08/11 03:53, , 18F
能不會 move 提供一個hint 給compiler
08/11 03:53, 18F

08/11 04:48, , 19F
Int long 的例子不太好 可能要user defined type 比較
08/11 04:48, 19F

08/11 04:48, , 20F
08/11 04:48, 20F

08/11 13:34, , 21F
可是unique_ptr不能copy,long轉int不能適用
08/11 13:34, 21F

08/11 14:21, , 22F
早上沒看推文xd 看來我誤解了
08/11 14:21, 22F

08/11 14:26, , 23F
一樓都講完了 會摳move constrictor
08/11 14:26, 23F
等等一樓講完了嗎我還不明白啊 Q_Q

08/12 20:11, , 24F
你應該先搞懂move semantics
08/12 20:11, 24F
最近一直在看相關的資料,包括yoco那篇文 但我發現自己連"會不會產生暫時物件"都有點分不清楚orz 繼續唸書.......

08/12 21:34, , 25F
推薦看effective modern C++ 去理解C++11
08/12 21:34, 25F
感謝!!!! ※ 編輯: james732 (223.137.25.206), 08/12/2016 22:24:51

08/13 21:33, , 26F
我發現這後面有很大的議題...
08/13 21:33, 26F
文章代碼(AID): #1NgqThSo (C_and_CPP)