微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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);

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

– -编辑 – –

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

换句话说,我知道如何使用STL容器(vector)和它们的迭代器(vector :: begin / end).我不知道是我问的.

尽管如此,希望有人能从答案中受益,如果不是我.

解决方法

你正在寻找的直接答案是 stdext::checked_array_iterator.这可以用来包装一个指针,它的长度是一个MSVC checked_iterator.

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

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

原文地址:https://www.jb51.cc/c/115483.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐