std::iterator、指针和 VC++ 警告 C4996

2023-12-28

int *arr = (int*) malloc(100*sizeof(int));
int *arr_copy = (int*) malloc(100*sizeof(int));
srand(123456789L);
for( int i = 0; i < 100; i++) {
    arr[i] = rand();
    arr_copy[i] = arr[i];
}

// ------ do stuff with arr ------

// reset arr...
std::copy(arr_copy, arr_copy+100,  arr);

编译时我收到此警告std::copy():

c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(2227):
warning C4996: 'std::_Copy_impl': Function call 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'

我知道如何禁用/忽略警告,但是是否有一种简单的单行解决方案可以从未经检查的指针中创建“经过检查的迭代器”?类似的东西(我知道 cout 不是像 int* 这样的未经检查的指针,但只是例如):

ostream_iterator<int>  out(cout," ");

std::copy(arr_copy, arr_copy+numElements,  out);

我不想写一个全新的专业class my_int_arr_output_iterator : iterator...。但我可以使用现有的迭代器之一吗?

- -编辑 - -

由于关于我使用 c 风格数组和 malloc 而不是 STL 容器有很多问题,我只想说我正在编写一个小程序来测试不同排序算法的性能和内存使用情况。您在上面看到的代码片段是特定于该问题的专用版本(原始代码是具有多种方法的模板类,针对不同类型的数组中的不同数量的元素测试一种算法)。

换句话说,我确实知道如何使用 STL 容器(向量)及其迭代器(向量::开始/结束)来做到这一点。我不知道的是I asked.

不过谢谢,希望其他人能从答案中受益,即使不是我。


您正在寻找的直接答案是stdext::checked_array_iterator http://msdn.microsoft.com/en-us/library/aa985928%28v=vs.80%29.aspx。这可用于将指针及其长度包装到 MSVC checked_iterator 中。

std::copy(arr_copy, arr_copy+100, stdext::checked_array_iterator<int*>(arr, 100) );

他们还提供stdext::checked_iterator http://msdn.microsoft.com/en-us/library/aa985943%28v=vs.80%29.aspx它可以包装非检查容器。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

std::iterator、指针和 VC++ 警告 C4996 的相关文章