假设我有以下代码:
int* intPtr = new int[5];
// ...do stuff...
现在我想将 intPtr 复制到一个新的、相同的数组:
int* newIntPtr = new int[5];
这可以使用简单的 for 循环或 std::copy() 来完成:
使用for循环
for (int i = 0; i < 5; i++) *(newIntPtr + i) = *(intPtr + i);
使用 std::copy()
std::copy( intPtr, intPtr + 5, newIntPtr );
使用 std::copy(),我在 Visual Studio 中收到警告:
warning C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe...
我可以使用stdext::checked_array_iterator<int*>
使警告消失:
std::copy(intPtr, intPtr + 5, stdext::checked_array_iterator<int*>(newIntPtr, 5));
但这意味着代码无法在 Visual Studio 以外的任何平台上编译。
那么,我该如何解决呢?我应该使用简单的 for 循环并有效地避免警告,还是应该使用 std::copy() 并采取一些措施来避免警告?显然,我可以禁用警告,但这似乎不是一个合适的解决方案……或者是这样吗?
最佳答案
在循环中使用 std::copy
有一些好处:
- 调用是自记录的。您通话的读者无需阅读评论或弄清楚循环在做什么就可以立即知道语句的意图
- 它可能会像您的情况一样针对简单类型进行优化:
In practice, implementations of std::copy avoid multiple assignments and use bulk copy functions such as std::memmove if the value type is TriviallyCopyable source
- 更易于维护。您的容器将来更容易更换。您只需要更改复制的参数而不是实现
正如其他评论所提到的,循环调用和复制调用同样不安全,因此警告具有误导性。但是,我会避免禁用整个应用程序的安全警告。相反,使用 #pragma disable
关于c++ - 使用 std::copy 而不是手动 for 循环复制动态数组有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29099564/