Cppreference states, regarding std::memcpy()
(emphasis added):
If the objects are potentially-overlapping or not TriviallyCopyable, the behavior of
memcpy
is not specified and may be undefined.
So, I always check to ensure an object IS trivially-copyable before using memcpy()
, like this:
#include <type_traits>
static_assert(std::is_trivially_copyable<T>::value, "Type T must "
"be a trivially-copyable type in order to guarantee that `memcpy()` is safe "
"to use on it.");
memcpy(&outputData, &data, sizeof(data));
std::copy()
, however, doesn't seem to have this limitation: https://en.cppreference.com/w/cpp/algorithm/copy.
Does this limitation that the type must be trivially-copyable to not have undefined behavior NOT apply to std::copy()
?
Also, I just realized in my "placement new" answer here, which made me wonder about this whole thing, I used just memcpy()
instead of std::memcpy()
, and I was not using namespace std;
, so which function was called? Is memcpy()
a different implementation from std::memcpy()
?
std::copy
is a simple standard algorithm. Its general version just uses assignment in a loop, so it is applicable in the same cases as assignment. Library implementers will usually have a special implementation ofstd::copy
throughmemcpy
when it is safe to do so and is faster than assignment. Sincememcpy
is a legacy C function, it should almost never be used in C++ outside low-level libraries,.::memcpy
andstd::memcpy
is really the same thing, because it is coming from C standard library. Formally, you should use::memcpy
if you#include <string.h>
andstd::memcpy
if you#include <cstring>
, but in practice::memcpy
is always available.