编程奥义:
bug1: 描述:《c++ primer plus》12章练习2 自定义类,并且重载 + 运算
String s1(" and I am a C++ student.");
String s2 = "Please enter your name: ";
String s3;
cout << s2;
cin >> s3;
s2 = "My name is " + s3;
cout << s2 << ".\n";
s2 = s2 + s1;
s2.stringup();
cout << "The string\n"
<< s2
<< "\ncontains "
<< s2.has('A') << " 'A' characters in it.\n";
预计输出: Please enter your name: 1213 My name is 1213. The string MY NAME IS 1213 AND I AM A C++ STUDENT. contains 4 ‘A’ characters in it.
实际输出(输出异常并且程序中断): Please enter your name: 11aa My name is 11aa. The string MY NAME IS 11AAUR NAME: AND I AM A C++ student. contains
可以看到,实际输出中,s2的部分字符串有残留。 残留字符串: UR NAME :
原因推测: 重载 + 运算符的时候,delete 之后 马上new, 因为之前字符串较长,所以刚好分配了原内存,如果不清空,就会有残留。 使用memset清空分配的空间后,回复正常。
String & String::operator+(const String &s)
{
char temp[String::CINLIM];
strncpy(temp, str, len);
delete []str;
str = new char[len+s.len+1];
strncpy(str, temp, len);
strncat(str, s.str, s.len);
len += s.len;
return *this;
}
|