2013-04-01 56 views
0

我的代碼有問題。我得到一個BLOCK_TYPE_IS_VALID的錯誤...我知道新的和刪除有問題,但我找不到它。 我有這些功能的類的myString:堆和類析構函數

//constructors and destructors 
myString::myString() { 
    this->string_ = NULL; 
    this->length = 0; 

    cout << "created " << "NULL" << endl; 
} 

myString::myString(char a[]) { 
    int i; 
    for (i=0; a[i]!=NULL; i++); 
    this->length = i; 

    int j=0; 
    while(pow(2,j)<i) 
     j++; 

    this->string_ = new char [(int)pow(2,j)]; 
    for (int i=0; i<this->length; i++) 
     this->string_[i] = a[i]; 

    cout << "created " << this->string_ << endl; 
} 

myString::~myString() { 
    cout << "deleteing " << this->string_ << endl; 
    if (this->string_ != NULL) 
     delete [] this->string_; 
} 

,當我運行此

​​

我得到線 「C = A + B」 的錯誤,然後程序停止。

+1

您需要在您的類中定義'operator +',以便程序知道如何添加字符串。 – Caesar

+1

您是否重載了運算符'+'&operator'='?你可以顯示該代碼嗎? – user93353

+1

根據我看到的代碼,我希望你已經定義了複製構造函數和賦值運算符。你可以顯示該代碼嗎? –

回答

1

您還沒有表現出類的定義,但我猜你沒有遵循Rule of Three

如果沒有正確實施的複製構造函數和複製賦值運算符,則不可能安全地複製對象。默認實現將簡單地複製指針(和其他成員變量),使兩個副本在其析構函數中刪除同一塊內存。

最簡單的解決方案是使用旨在爲您管理內存的類。 std::stringstd::vector<char>將是理想的。

假設你有一個很好的理由爲自己管理的內存,您將需要類似:

// Copy constructor 
myString(myString const & other) : 
    string_(new char[other.length]), 
    length(other.length) 
{ 
    std::copy(other.string_, other.string_+length, string_); 
} 

// Simple assignment operator 
// For bonus points (and a strong exception guarantee), use the copy-and-swap idiom instead 
myString & operator=(myString const & other) { 
    if (this != &other) { 
     delete [] string_; // No need to check for NULL (here or in the destructor) 
     string_ = new char[other.length]; 
     length = other.length; 
     std::copy(other.string_, other.string_+length, string_); 
    } 
    return *this; 
} 

在C++ 11,甚至更多的積分,考慮還提供了移動構造函數和賦值操作符。這些只需要修改指針,所以比複製效率更高。

+0

非常感謝,我從你的代碼中學到了很多東西 – Ramyad

3

您需要爲您的班級定義copy constructorassignment operator

否則,您違反了rule of three

此代碼...

c = a + b; 

可能會產生暫時性myString持有價值a + b

默認生成的複製和分配實現將給c指針0123,指針臨時具有

而當這些字符串的析構函數運行時,另一個字符串將有一個懸掛指針。

巧合的是,此代碼:

if (this->string_ != NULL) 
    delete [] this->string_; 

絕不會採取不同的不是簡單:

delete [] this->string_; 
+0

謝謝,我很困惑。現在我明白髮生了什麼。 – Ramyad