Date
2018-03-16.00:00:00
Message id
9777

Content

Table 54, Character traits requirements, says that char_traits::move allows the ranges to overlap, but char_traits::copy requires that p is not in the range [s, s + n). This appears to be an attempt to map to the requirements of memmove and memcpy respectively, allowing those to be used to implement the functions, however the requirements for copy are weaker than those for memcpy. The C standard says for memcpy "If copying takes place between objects that overlap, the behavior is undefined" which is a stronger requirement than the start of the source range not being in the destination range.

All of libstdc++, libc++ and VC++ simply use memcpy for char_traits<char>::copy, resulting in undefined behaviour in this example:

char p[] = "abc";
char* s = p + 1;
std::char_traits<char>::copy(s, p, 2);
assert(std::char_traits<char>::compare(p, "aab", 3) == 0);

If the intention is to allow memcpy as a valid implementation then the precondition is wrong (unfortunately nobody realized this when fixing char_traits::move in LWG DR 7). If the intention is to require memmove then it is strange to have separate copy and move functions that both use memmove.

N.B. std::copy and std::copy_backward are not valid implementations of char_traits::copy either, due to different preconditions.

Changing the precondition implicitly applies to basic_string::copy ([string.copy]), and basic_string_view::copy ([string.view.ops]), which are currently required to support partially overlapping ranges:

std::string s = "abc";
s.copy(s.data() + 1, s.length() - 1);
assert(s == "aab");