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

Kas*_*yap 11 c++ algorithm iterator stl

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);
Run Code Online (Sandbox Code Playgroud)

在编译时,我得到以下警告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'
Run Code Online (Sandbox Code Playgroud)

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

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

std::copy(arr_copy, arr_copy+numElements,  out);
Run Code Online (Sandbox Code Playgroud)

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

- -编辑 - -

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

换句话说,我知道如何使用STL容器(向量)及其迭代器(vector :: begin/end)来完成此操作.我不知道的是我问的问题.

谢谢,希望如果不是我,其他人会从答案中受益.

Dav*_*e S 16

您正在寻找的直接答案是stdext :: checked_array_iterator.这可用于将指针及其长度包装到MSVC checked_iterator中.

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

它们还提供了一个stdext :: checked_iterator,它可以包装一个未经检查的容器.

  • 不便携,但回答我的问题.. :)谢谢. (2认同)
  • @thekashyap:嗯,我认为任何解决方案都是不可移植的,因为这种检查迭代器的味道是MSVC的东西,我希望解决方案也是如此. (2认同)
  • 他们不再拥有MSVS 2010的`stdext :: checked_iterator`了.只有MSVS 2005和2008才有.然而`checked_array_iterator`就在那里并且效果很好. (2认同)

Pet*_*ker 7

这是一个"母亲,可能我"警告:代码是正确的,但图书馆作者认为你不够聪明,无法处理它.关掉愚蠢的警告.


Luc*_*ore 6

这是一个:

std::vector<int> arr(100);
std::vector<int> arr_copy(100);
srand(123456789L);
for( int i = 0; i < 100; i++) {
    arr[i] = rand();
    arr_copy[i] = arr[i];
}

//do stuff

std::copy(arr_copy.begin(), arr_copy.end(), arr.begin());
Run Code Online (Sandbox Code Playgroud)

  • 虽然没有真正回答这个问题.我很好奇是否有办法真正"修复"这个警告,而不是沉默或颠覆它. (3认同)