[問題] unique_ptr與move

作者: james732 (好人超)   2016-08-10 23:25:24
問題(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呢?
如果不這麼寫的話又會造成什麼問題?
(想知道這個寫法的反例?)
作者: Caesar08 (Caesar)   2016-08-10 23:40:00
因為不這麼做,不能通過compile?可是我在MSVC跟GCC上,又都能通過compile...對於要convert type的unique_ptr,unique_ptr的constructor只接受r value。所以應該是這原因導致要move可能是return value都會當作r value,然後能用RVO的就用所以就剛好可以通過編譯了吧。以上是我的猜測,請求支援
作者: EdisonX (卡卡獸)   2016-08-11 00:54:00
#19gioP8j Page9~12 , 講八個 string 相加的問題不推別人會以為看不懂啊! @@
作者: steve1012 (steve)   2016-08-11 03:47:00
你這樣問好像有點誤導 點進去才知道unique Ptt 是個例子簡單來說 return 一個不match 像是要int 你return long有可能有copy 發生使用move 可以確保不會有copy 因爲compiler 讀到知道不能copy要是我想的沒有錯的話 這個應該是建議而非require這裡提到這個的原因是因為簡單的情況下compiler 可以自己採用move semantics 但複雜的情況 要cast的情況可能不會 move 提供一個hint 給compilerInt long 的例子不太好 可能要user defined type 比較好
作者: Caesar08 (Caesar)   2016-08-11 13:34:00
可是unique_ptr不能copy,long轉int不能適用
作者: steve1012 (steve)   2016-08-11 14:21:00
早上沒看推文xd 看來我誤解了一樓都講完了 會摳move constrictor
作者: bluesoul (忙死你老爸)   2016-08-12 20:11:00
你應該先搞懂move semantics
作者: druid0214 (Assassin)   2016-08-12 21:34:00
推薦看effective modern C++ 去理解C++11
作者: Caesar08 (Caesar)   2016-08-13 21:33:00
我發現這後面有很大的議題...

Links booklink

Contact Us: admin [ a t ] ucptt.com