Suppose I have the following code:
int* intPtr = new int[5];
// ...do stuff...
And now I want to copy intPtr to a new, identical, array:
int* newIntPtr = new int[5];
This can be done using either a simple for-loop or std::copy():
Using a for loop
for (int i = 0; i < 5; i++)
*(newIntPtr + i) = *(intPtr + i);
Using std::copy()
std::copy( intPtr, intPtr + 5, newIntPtr );
Using std::copy(), I get a warning in Visual Studio:
warning C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe...
I could use stdext::checked_array_iterator<int*>
to make the warning go away:
std::copy(intPtr, intPtr + 5, stdext::checked_array_iterator<int*>(newIntPtr, 5));
but that means the code won't compile on anything else than Visual Studio.
So, how should I solve this? Should I use the simple for loop and effectively avoid the warning, or should I use std::copy() and do something to avoid the warning? Obviously, I could disable the warning, but that doesn't seem like a proper solution... or is it?
There are a few benefits for using std::copy
over a loop:
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
As other comments have mentioned, both, the loop and copy calls are equally unsafe so the warning is misleading. However, I would avoid disabling security warnings for the whole application. Instead, disable locally with #pragma disable
The most obvious advantage is that using std::copy
says explicitly
what you are doing. The reader doesn't have to analyse the loop to
figure it out. A second advantage is that it is less lines of code.
This isn't an absolute advantage; sometime being a little more verbose
is better. But when you use less lines of code to make the code
clearer, it's definitely an advantage.
For the rest: in theory, the compiler could have built-in knowledge of a standard function, and apply optimizations that it wouldn't be able to find for a user written function or a loop. In practice, I don't know of any compiler which does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With