2010-12-22 123 views
0

我想了解這個複製構造函數問題。在程序退出後,我遇到了與析構函數有關的問題。看來可變char *標題沒有被破壞,我想這可能是錯誤的,謝謝複製構造函數問題

另一個問題是爲什麼當對象x等於x2時不會調用賦值運算符。我使用g ++和codeblocks。

#include <iostream> 

using namespace std; 

class myClass 
{ 
    private: 

     int x; 
     int *p; 
     char* title; 

    public: 

     myClass(int tx, int* temp, char* newtitle) 
     { 
      x = tx; 
      cout << "int constructor called with value x = " << x << endl; 

      p = new int; 
      p = temp; 

      title = new char [strlen(newtitle)+1]; 
      strcpy(title, newtitle); 
     } 
     myClass(const myClass& mc) 
     { 
      cout << "copy constructor called with value = " << mc.x << endl; 
      x = mc.x; 
      p = new int; 
      *p = *mc.p; 

      title = new char [strlen(mc.title)+1]; 
      strcpy(title, mc.title); 
     } 
     myClass & operator = (const myClass & that) 
     { 
      cout << "assignment called" << endl; 

      if(this != &that) 
      { 
       x = that.x; 
      } 
      return *this; 
     } 
     ~myClass() 
     { 
      if (p) 
      { 
       cout<<"deleting p"<<endl; 
       delete p; 
      } 
      else if(title) 
      { 
       cout<<"deleting title"<<endl; 
       delete[] title; 
      } 
     } 
}; 

int main() 
{ 
    int pointee = 10; 
    int* p = &pointee; 
    myClass x(3,p,"hello"); 
    //myClass y = myClass(3,p); 
    myClass x2 = x; 
    return 0; 
} 
+0

修復了您的格式。 – 2010-12-22 17:13:52

+3

也許你需要在析構函數中使用「if(title)」而不是「else if(title)」 – DReJ 2010-12-22 17:15:37

回答

3

您在我的實際代碼和一般方法中都能看到各種各樣的問題。

首先,char * title不會被刪除,因爲您不會刪除它。這可能是一個邏輯錯誤:

if (p) 
    { 
     cout<<"deleting p"<<endl; 
     delete p; 
    } 
    else if(title) 
    { 
     cout<<"deleting title"<<endl; 
     delete[] title; 
    } 

您可能不需要else。你爲什麼把它放在那裏?

接下來,你都滲出了int,在這裏:

p = new int; 
    p = temp; 

int你只是new -ed得到由傳入的價值temp覆蓋。

後來,您嘗試在析構函數中刪除此指針。但是因爲你正在刪除一個指向自動變量的指針,所以你會把這個堆放到一個地方。這也是一個邏輯錯誤。解決方案:不要這樣做:p = temp;

然而,最終,您的方法在多個層面上是有問題的。

  1. 爲什麼你首先動態分配int?只需要有一個int班的成員。不要使用動態分配(例如newdelete),除非你真的必須。
  2. 請勿使用char* s動態分配字符串。相反,使用std::string#include <string>
  3. 如果你確實是需要動態分配,請不要使用原始指針。改用智能指針。 C++自帶一個內置的std::auto_ptr#include <memory.h>,但在其他庫中有許多其他選項,通常是更好的選擇。這裏頗受歡迎的是Boost的智能指針。
1

你的析構函數刪除p如果p是非NULL;如果它不是NULL,則它刪除titlep爲NULL

但是你的構造函數和拷貝構造函數都會一直創建new pnew title。所以你需要一直檢查和刪除。

0

嘗試

*p = *temp; 

代替

p = temp; 

,並在析構函數

if(title) 

,而不是

else if(title)