Mag*_*s W 2 c++ arrays deep-copy visual-studio c++11
假设我有以下代码:
int* intPtr = new int[5];
// ...do stuff...
Run Code Online (Sandbox Code Playgroud)
现在,我想将intPtr复制到一个相同的新数组中:
int* newIntPtr = new int[5];
Run Code Online (Sandbox Code Playgroud)
这可以使用简单的for循环或std :: copy()来完成:
使用for循环
for (int i = 0; i < 5; i++)
*(newIntPtr + i) = *(intPtr + i);
Run Code Online (Sandbox Code Playgroud)使用std :: copy()
std::copy( intPtr, intPtr + 5, newIntPtr );
Run Code Online (Sandbox Code Playgroud)
使用std :: copy(),我在Visual Studio中收到警告:
warning C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe...
Run Code Online (Sandbox Code Playgroud)
我可以使用stdext::checked_array_iterator<int*>,使报警消失:
std::copy(intPtr, intPtr + 5, stdext::checked_array_iterator<int*>(newIntPtr, 5));
Run Code Online (Sandbox Code Playgroud)
但这意味着代码将无法在Visual Studio之外的任何其他语言上编译。
那么,我该如何解决呢?我应该使用简单的for循环并有效地避免该警告,还是应该使用std :: copy()并采取某些措施来避免该警告?显然,我可以禁用该警告,但这似乎不是一个适当的解决方案……或者是吗?