[問題] copy constructor and operator= 的覆寫

看板C_and_CPP (C/C++)作者 (☆㊣↖煞氣ㄟ阿喂↘ξ★)時間16年前 (2010/03/06 19:36), 編輯推噓4(409)
留言13則, 6人參與, 最新討論串1/1
一般書上說當你的class有含指標時,要自己寫copy constructor以及覆寫operator= 如果我一個class像這樣: class A{ int* ptr; double x; int y; ..... ..... A( const A& rhd ); A& operator=( const A& rhd ); ////....尚有一堆data member..... //// }; 那我要另外寫一個copy constructor: A::A( const A& rhd ){ this->ptr = new int(0); *this->ptr = *rhd.ptr; this->x = rhd.x; this->y = rhd.y; .... .... //// .......... 其他data member也要複製......///// } //// operator= 複寫也一樣 //// 我的問題是如果data member有很多,那我一個一個寫在copy constructor內不就很笨? 有更快的或更方便的作法嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 202.132.128.158

03/06 19:40, , 1F
member過多通常可能是你設計不良
03/06 19:40, 1F

03/06 19:41, , 2F
應該是沒有比較快的方法, 但是copy ctpr可以呼叫
03/06 19:41, 2F

03/06 19:41, , 3F
operator= , 然後都在operator=內實作
03/06 19:41, 3F

03/06 19:43, , 4F
同a大, 可能你責任分配不均,有的可以用local variable
03/06 19:43, 4F

03/06 19:43, , 5F
或外部的物件來幫忙
03/06 19:43, 5F

03/06 20:33, , 6F
copy ctor呼叫operator不太好吧...@@
03/06 20:33, 6F

03/06 20:57, , 7F
是沒錯啦...這樣會慢很多
03/06 20:57, 7F

03/06 21:06, , 8F
該寫的不能省 > __ <
03/06 21:06, 8F

03/07 04:45, , 9F
乖乖寫吧,問這問題+煩惱的時間,code 都打完了。
03/07 04:45, 9F

03/07 10:58, , 10F
聽說過 Symbian的SDK ctor 是用串的 找找design pattern?
03/07 10:58, 10F

03/09 12:29, , 11F
如果poniter效率不是非常critical 就用smart pointer
03/09 12:29, 11F

03/09 12:30, , 12F
代替吧 這樣就不用自己寫operator=和copy ctor
03/09 12:30, 12F

03/09 12:31, , 13F
像是boost::shared_ptr之類的
03/09 12:31, 13F
文章代碼(AID): #1BaZvMYB (C_and_CPP)
文章代碼(AID): #1BaZvMYB (C_and_CPP)