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()
?