Reputation: 131586
The standard library offers std::copy
, which can be seen as a generalization/generification of C's memcpy()
. It also maintains the requirement of memcpy()
, for the range [first
, last
) to be disjoint from the range [d_first
, d_first + std::distance(first, last)
); otherwise we have undefined behavior.
My question: Is there a generic version of std::memmove
(i.e. which doesn't make that requirement and would typically be implemented using a temporary buffer)? If not, how come?
Upvotes: 3
Views: 921
Reputation: 75707
C++ doesn't have drop in replacements for memcpy
and memmove
.
For non-overlapping ranges usually std::copy
is used, but std::copy_backwards
can also be used.
For overlapping ranges you need to use std::copy
or std::copy_backwards
depending on the nature of the overlap.
Also for copy-expensive objects std::move
(<algorithm>
) and std::move_backward
respectively can be used instead if the original objects don't need to keep their value.
template< class InputIt, class OutputIt > OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
Copies the elements in the range, defined by [first, last), to another range beginning at d_first.
Copies all elements in the range [first, last) starting from first and proceeding to last - 1. The behavior is undefined if d_first is within the range [first, last). In this case, std::copy_backward may be used instead.
Notes
When copying overlapping ranges, std::copy is appropriate when copying to the left (beginning of the destination range is outside the source range) while std::copy_backward is appropriate when copying to the right (end of the destination range is outside the source range).
template< class BidirIt1, class BidirIt2 > BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last );
Copies the elements from the range, defined by [first, last), to another range ending at d_last. The elements are copied in reverse order (the last element is copied first), but their relative order is preserved.
The behavior is undefined if d_last is within (first, last]. std::copy must be used instead of std::copy_backward in that case.
Notes
When copying overlapping ranges, std::copy is appropriate when copying to the left (beginning of the destination range is outside the source range) while std::copy_backward is appropriate when copying to the right (end of the destination range is outside the source range).
Upvotes: 5