C4996 std::basic_string错误解决方案

使用basic_string类的成员函数copy()时会报C4996错误

str1.copy(str, 1, 0);

//报错:
/*
错误  C4996
'std::basic_string,std::allocator>::copy': Call to 'std::basic_string::copy' with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'  
*/

查找MSDN得知,该成员函数因为可能存在下标越界风险已经被弃用,并提供了basic_string::_Copy_s 代替 basic_string::copy

代替后:

str1._Copy_s(str, 1, 0);

//通过编译

也可以通过预处理禁用该警告的方式消除警告:

#pragma warning(disable:4996)
str1.copy(str, 1, 0);

//无警告,通过编译。

你可能感兴趣的:(#,C,/,C++)