For an iterator ptr
which is a pointer, std::fill_n(ptr, n, 0)
should do the same thing as memset(ptr, 0, n * sizeof(*ptr))
(but see @KeithThompson's comment on this answer).
For a C++ compiler in C++11/C++14/C++17 mode, under which conditions can I expect these to be compiled to the same code? And when/if they don't compile to the same code, is there a significant performance difference with -O0? -O3?
Note: Of course some/most of the answer might be compiler-specific. I'm only interested in one or two specific compilers, but please write about the compiler(s) for which you know the answer.
The answer depends on your implementation of the standard library.
MSVC for example has several implementations of
std::fill_n
based on the types of what you're trying to fill.Calling
std::fill_n
with achar*
orsigned char*
orunsigned char*
and it will directly callmemset
to fill the array.If you call with another type, it will fill in a loop:
The best way to determine the overhead on your particular compiler and standard library implementation would be to profile the code with both calls.