[問題] destructor

看板C_and_CPP (C/C++)作者 (不離不泣被當北七)時間16年前 (2010/04/13 14:31), 編輯推噓3(302)
留言5則, 4人參與, 最新討論串1/1
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 ) 遇到的問題: (題意請描述清楚) program crash 希望得到的正確結果: no error, 想問一下C's destructor要怎麼改 才不會出現錯誤(crash) 程式跑出來的錯誤結果: C's destructor有寫錯 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Dev-C++ 有問題的code: (請善用置底文標色功能) #include<iostream> using namespace std; class A{ private: int a_; public: static double db_; A(int a=0):a_(a){cout<<"A's constructor"<<endl;} virtual ~A(){cout<<"A's destructor"<<endl;} }; double A::db_=0; class B:public A{ private: int b_; public: B(int b=0):b_(b){cout<<"B's constructor"<<endl;} B(const B&); ~B(){cout<<"B's destructor"<<endl;} }; B::B(const B& src){ this->b_= src.b_; cout<<"B's copy constructor"<<endl; } class C{ B *pb_; public: C():pb_(new B){cout<<"C's constructor"<<endl;} C(const C&); const C& operator=(const C&); virtual ~C(){cout<<"C's destructor"<<endl; delete pb_; } }; C::C(const C& src):pb_(new B){ pb_=src.pb_; cout<<"C's copy constructor"<<endl; } const C& C::operator=(const C& rhs){ this->pb_=rhs.pb_; cout<<"C's Assign Operator"<<endl; return *this; } int main(){ C c1; C c2; c2=c1; getchar(); return 0; } 補充說明: -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 160.39.43.40 ※ 編輯: tiwei 來自: 160.39.43.40 (04/13 14:31)

04/13 14:41, , 1F
C 裡面的 pb_ 被 delete 兩次
04/13 14:41, 1F

04/13 14:46, , 2F
C 的 copy ctor會造成memory leak
04/13 14:46, 2F

04/13 19:11, , 3F
那要如何改呢?
04/13 19:11, 3F

04/13 19:36, , 4F
你覺得呢?先別偷看解答,想看看怎麼解決如何?
04/13 19:36, 4F

04/13 19:39, , 5F
沒看邏輯 但你幹嘛幫pb new阿 在C的copy ctrs
04/13 19:39, 5F
文章代碼(AID): #1Bn0-fO2 (C_and_CPP)
文章代碼(AID): #1Bn0-fO2 (C_and_CPP)