软件缺陷实验
软件缺陷实验:#include <string.h>
#include <iostream>
using namespace std;
class MyString
{
public:
char *mChars;
MyString()
{
mChars = new char;
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;
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 0;
}
结果截图:
取消注释后:
加上注释后:
断点调试:
在“=”重载操作中,如果涉及指针操作,则必须判断两个对象是否为同一个对象,否则指针*p执行了两次释放操作中,可能会造成死机。
如果在上面的程序中,缺少if(&rhs==this) return *this,则指针将会被释放两次。
今天软件测试课讲得,其实也不是特别理解。当去掉注释的时候,两个a值是一样的,后续弄懂更,先记录一下。。。
学习 学习
页:
[1]