注册 登录
编程论坛 C++教室

运算符重载问题

lam888888908 发布于 2012-01-29 09:54, 473 次点击
61   // concatenate right operand to this object and store in this object
62   const String &String::operator+=( const String &right )
63   {
64      size_t newLength = length + right.length; // new length
65      char *tempPtr = new char[ newLength + 1 ]; // create memory
66
67      strcpy( tempPtr, sPtr ); // copy sPtr这里
68      strcpy( tempPtr + length, right.sPtr ); // copy right.sPtr这里
69
70      delete [] sPtr; // reclaim old space
71      sPtr = tempPtr; // assign new array to sPtr
72      length = newLength; // assign new length to length
73      return *this; // enables cascaded calls
74   } // end function operator+=
编译时提示:warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
67行我改成:strcpy_s( tempPtr,newLength+1, sPtr )通过了
68行我不会改,请高手看下!
2 回复
#2
rjsp2012-01-29 11:18
我建议你不要理睬这个微软的警告,因为这个警告很傻屄
如果strcpy是不安全的,可能溢出,则strcpy_s同样也是不安全的,也可能溢出
如果用户使用strcpy_s时考虑到溢出而安全,同样用户在使用strcpy时考虑到溢出而一样安全
如果溢出,strcpy在运行时出错,strcpy_s则不。即后者会深深的隐藏住这个bug,从而带来数据错误等更为严重的后果
另外strcpy_s等微软特有的垃圾是非标准的

如果想屏蔽掉这个傻逼警告,进引入strcpy的头文件之前加上 #define _CRT_SECURE_NO_WARNINGS

如果你一定要用strcpy_s
strcpy( tempPtr, length+1, sPtr );
strcpy( tempPtr+length, right.length+1, right.sPtr );
#3
lam8888889082012-01-29 12:45
谢了
1