Re: [問題]使用Union問題

看板C_and_CPP作者 (朴髮箍)時間14年前 (2011/04/30 19:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/3 (看更多)
※ 引述《karcher (一個project值多少~~)》之銘言: : 問題(Question): : 使用Union, but Compile Failed : struct Test : { : union : { : std::string str; : int num; : }; : }; : Compile failed .... : Does anybody have a good idea to solve this?? 請參考 9.5/1 [...] A union can have member funcitons(including constructors and destructors), but not virtual functions. A union shall not have base classes. A union shall not be used as a base class. An object of a class with a non-trivial constructor, a non-trivial copy constructor, a non-trivial destructor, or a non-trivial assignment operatror cannot be a member of a union, nor can an array of such objects[...] 簡單來記, union 裡面不要裝除了 POD 以外的東西就對了. 因為記 憶體是共用的關係, 當你存取 num 時, 很可能改變到 str 的狀態 , 造成後續程式碼發生存取違規的錯誤, 有一點很重要: 1. non-trivial copy constructor 2. non-trivial destructor 3. non-trivial assignment operatror 當一個類別規格定義了上述 3樣東西 (最好全部都有, 要不然就是 全部都沒有), 很可能它在複製的時候所作的是 deep copy 而不是 shallow copy, 這時候能代表物件狀態的就不僅僅是記憶體的值而 已, 應該要受到它所提供的介面來保護. 你沒要應用, 我不知道要給你怎樣的解決方案. 除非有特殊需求, 平常我不會用到 union這東西, 因為就概念來說 , 一個物件可以當成 std::string來用, 也可以當成 int來用, 那 麼這些性質應該分屬於不同的類別, 而不是全部加在一起. -- ▂▂ ▄▂ T.T.L Listen 2 http://ppt.cc/jIUk ˇ ˇˇ ˇ 說什麼結束 ▃▃ http://ppt.cc/zQtB ψ髮箍 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.121.197.115 ※ 編輯: loveme00835 來自: 140.121.197.115 (04/30 19:14)
文章代碼(AID): #1Dk-vEtW (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1Dk-vEtW (C_and_CPP)