[問題] copy&swap idiom & C++11 move semantics

看板C_and_CPP (C/C++)作者時間12年前 (2013/07/08 18:19), 編輯推噓2(208)
留言10則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VS2012, GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): Exceptional C++ 有一個手法是寫Exception-Safe的程式碼 其中operator=會用copy constructor和swap來達到Exception-Safe 舉例: C++98下 class CMyClass { public: // big three public: void swap(CMyClass& rhs); private: std::string m_sID; } CMyClass::CMyClass(const CMyClass& rhs) : m_sID(rhs.m_sID) {} CMyClass& CMyClass::operator=(const CMyClass& rhs) { CMyClass tmp(rhs); // 會這樣使用 swap(tmp); return *this; } void CMyClass::swap(CMyClass& rhs) { m_sID.swap(rhs.m_sID); } 現在問題是, 當我加入了C++11 move semantics CMyClass::CMyClass(CMyClass&& rhs) : m_sID(std::move(rhs.m_sID)) {} CMyClass& CMyClass::operator=(CMyClass&& rhs) { CMyClass tmp(std::move(rhs)); swap(std::move(tmp)); // 問題, 該不會要寫個void swap(CMyClass&& rhs)吧? return *this; } 我看std內的map沒在實做rvalue reference這種swap的, 這表示我也不應該實做這種swap吧? 怎麼在move assignment寫出正確的Exception-Safe code呢? 謝謝! 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 36.231.16.171 ※ 編輯: LenaPark 來自: 36.231.16.171 (07/08 18:26)

07/08 18:57, , 1F
有rvalue ref就不用再copy啦,直接和rhs做swap就行了
07/08 18:57, 1F

07/08 21:24, , 2F
對喔!好像是個蠢問題.
07/08 21:24, 2F

07/08 21:28, , 3F
不過直接swap是不是就沒有用到move semantics的好處了?
07/08 21:28, 3F

07/08 21:30, , 4F
似乎搜尋到的都是move=內直接寫
07/08 21:30, 4F

07/08 21:31, , 5F
m_sID = std::move(rhs.m_sID);
07/08 21:31, 5F

07/08 21:31, , 6F
不過這樣有兩個以上的成員變數就不是exception-safe了
07/08 21:31, 6F

07/08 21:55, , 7F
怎麼會沒利用到move咧,它省了一次copy
07/08 21:55, 7F

07/08 21:56, , 8F
重點並不是有沒有呼叫std::move,而是有沒有節省copy
07/08 21:56, 8F

07/08 21:58, , 9F
有swap就全部用swap即可,這樣增加成員時才不會漏寫
07/08 21:58, 9F
※ 編輯: LenaPark 來自: 36.231.16.171 (07/09 09:37)

07/09 09:41, , 10F
謝謝!直接swap是最好的.
07/09 09:41, 10F
文章代碼(AID): #1Hsf92fS (C_and_CPP)
文章代碼(AID): #1Hsf92fS (C_and_CPP)