Re: [問題]使用Union問題
: 請參考 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 constructor
: 2. non-trivial copy constructor
: 3. non-trivial assignment operatror
對喔!!std::string三項都違反了
如果要裝載有關字串的訊息,
還是以char* or char temp[some_length]比較好??
: 當一個類別規格定義了上述 3樣東西 (最好全部都有, 要不然就是
: 全部都沒有), 很可能它在複製的時候所作的是 deep copy 而不是
: shallow copy, 這時候能代表物件狀態的就不僅僅是記憶體的值而
: 已, 應該要受到它所提供的介面來保護.
: 你沒要應用, 我不知道要給你怎樣的解決方案.
: 除非有特殊需求, 平常我不會用到 union這東西, 因為就概念來說
: , 一個物件可以當成 std::string來用, 也可以當成 int來用, 那
: 麼這些性質應該分屬於不同的類別, 而不是全部加在一起.
我想C++會支援union,大概也是因為C的緣故。
C語言的物件使用比較單純,
struct裡面都有預設的constructor, copy constructor、assignment
可是C++不是這是單純。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.25.185.223
→
04/30 19:33, , 1F
04/30 19:33, 1F
推
04/30 20:04, , 2F
04/30 20:04, 2F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):
問題
1
9