軟體缺陷實驗:
#include <string.h>
#include <iostream>
using namespace std;
class MyString
{
public:
char *mChars;
MyString()
{
mChars = new char[strlen("default value")+];
strcpy(mChars,"default value");
}
MyString& operator=(const MyString& rhs);
};
MyString& MyString::operator =(const MyString& rhs)
{
/*if(&rhs==this)
return *this;*/
if(rhs.mChars != NULL)
{
delete []mChars;
mChars = new char[strlen(rhs.mChars)+];
strcpy(mChars,rhs.mChars);
}
else
{
mChars = NULL;
}
return *this;
}
int main()
{
MyString a;
cout<<"a.mChars is "<<a.mChars<<endl;
a=a;
cout<<"a.mChars is"<<a.mChars<<endl;
return ;
}
結果截圖:
取消注釋後:
加上注釋後:
斷點調試:
在“=”重載操作中,如果涉及指針操作,則必須判斷兩個對象是否為同一個對象,否則指針*p執行了兩次釋放操作中,可能會造成當機。
如果在上面的程式中,缺少if(&rhs==this) return *this,則指針将會被釋放兩次。
今天軟體測試課講得,其實也不是特别了解。當去掉注釋的時候,兩個a值是一樣的,後續弄懂更,先記錄一下。。。